Room DB SQLite查询,用于从不同的表中获取一对多关系的计数

wxclj1h5  于 2022-12-04  发布在  SQLite
关注(0)|答案(1)|浏览(176)

我试图在查询中获得一对多关系的计数。
我的数据类:

data class CustomerWithCounts(
@Embedded val customer: Customer,
@Embedded val address: Address,
val orderCount: Int,
val paymentCount: Int
)

我在努力想怎么才能得到计数。
我的当前查询:

SELECT *, 
COUNT(SELECT * FROM tblOrder WHERE customerId = c.id) AS 'orderCount', 
COUNT(SELECT * FROM tblPayment WHERE customerId = c.id) AS 'paymentCount'
FROM tblCustomer c 
LEFT JOIN tblAddress a ON c.customerBillingAddressId = a.addressId 
ORDER BY c.customerFirstName, c.customerLastName

我该如何做到这一点?

but5z9lq

but5z9lq1#

假设您有两个具有一对多相关性的数据表-“Table 1”和“Table 2”,您可以使用下列SQLite查询来取得一对多相关性的计数:

SELECT Table1.id, COUNT(Table2.id) AS Count 
FROM Table1 
LEFT OUTER JOIN Table2 
ON Table1.id = Table2.Table1Id 
GROUP BY Table1.id;

相关问题