Get count of rows in table A that have a reference

2020-05-09 13:38发布

问题:

I am left joining two tables, 'device' and 'unit'. Device defines the type of device and an unit is an unique device that points to a row in the device table, defining its type.

I am now searching for a solution to select every device type from 'device' and counting how many units are there pointing to this device. The problem I am confronted with in my current solution,

SQL:

SELECT device.*, COUNT(unit.id) 
FROM device LEFT JOIN unit ON device.id = unit.device_id GROUPBY device.id

Scala Slick:

def devicesWithUnitCount = for {
    (device, unit) <- TableQuery[TDDevice] joinLeft TableQuery[TDUnit] 
                                           on (_.id === _.deviceID) 
                                           groupBy (_._1)
} yield (device, unit.size)

is that I get a count result of at least 1, even if there is no unit pointing to the device type.

How can I achieve this counting in SQL, or preferably Slick?

回答1:

Your SQL is correct for what you want to do. Slick is probably producing a query like this:

SELECT device.*, COUNT(device.id) 
-----------------------^
FROM device LEFT JOIN
     unit
     ON device.id = unit.device_id
GROUP BY device.id;

Maybe there is a way to get it to count device_id, which is unamibiguously from unit.