Get count of rows in table A that have a reference to table B

一曲冷凌霜 提交于 2019-12-04 06:48:57

问题


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.



来源:https://stackoverflow.com/questions/32813118/get-count-of-rows-in-table-a-that-have-a-reference-to-table-b

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!