Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Room DB SQLite query to get counts of one-to-many relationships from different tables

I’m trying to get a count of a one-to-many ralationship in my query.

My data class:

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

I’m struggling to figure out how I can get the counts.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My current Query:

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

How do I achieve this?

>Solution :

Assuming you have two tables – "Table1" and "Table2" – with a one-to-many relationship, you can use the following SQLite query to get the counts of the one-to-many relationships:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading