我正在搜索我在stackoverflow(Get count of rows in table A that have a reference to table B)
上找到的特定SQL但是我似乎无法在Slick中实现这个SQL解决方案。
SELECT device.*, c.cnt
FROM device
LEFT JOIN (SELECT device_id, COUNT(*) AS cnt
FROM unit
GROUP BY device_id) c
ON device.id = c.device_id
我当前的方法失败了
slick.SlickException: Unexpected node Select _2 -- SQL prefix: select x2.x3, x2.x4, x2.x5, x2.x6,
尝试运行/编译查询时
val devicesWithUnitCountResult = dbConfig.db.run(TableQueries.devicesWithUnitCount.result)
当前代码:
def unitCountPerDevice = for {
(id, length) <- TableQuery[TDUnit].groupBy(k => k.deviceID).map(k => (k._1, k._2.map(_.id).length))
} yield (id, length)
def devicesWithUnitCount = for {
(device, unitcount) <- TableQuery[TDDevice].joinLeft(unitCountPerDevice).on(_.id === _._1).map(k => {
val u = k._2.getOrElse((0, 0))._2
(k._1, u)
})
} yield (device, unitcount)
有人可以帮助我找出我在这里失败的地方吗?
答案 0 :(得分:2)
以这种方式试试
def unitCountPerDevice = TableQuery[TDUnit].groupBy(k => k.deviceID).map(k => (k._1, k._2.map(_.id).length))
def devicesWithUnitCount = TableQuery[TDDevice].joinLeft(unitCountPerDevice).on(_.id === _._1).map(d =>(d._1,d._2.map(_._2)))