我有一个BLOB列,我希望与其他列同时选择,另一个表中的关联行数COUNT。这就是我所拥有的:
SELECT locations.id, locations.name, photo,
COUNT(items.id) OVER (PARTITION BY locations.id) AS num_items
FROM locations
LEFT OUTER JOIN items ON locations.id = items.location_id
ORDER BY locations.name ASC
photo
是BLOB列。此查询获取了我想要的所有数据,但我看到每个location
的 x 行,其中 x 是与item
相关联的行数location
。
所以我得到了:
id name photo num_items
1 location1 3
1 location1 3
1 location1 3
2 location2 1
3 location3 2
3 location3 2
4 location4 0
我想要的是什么:
id name photo num_items
1 location1 3
2 location2 1
3 location3 2
4 location4 0
问题是您无法在DISTINCT
列上执行GROUP BY
,MIN
或BLOB
。
答案 0 :(得分:1)
我似乎总是在发布后立即找出答案。 :P
SELECT location_data.*, photo
FROM (
SELECT locations.id, locations.name, COUNT(DISTINCT items.id) AS num_items
FROM locations
LEFT OUTER JOIN items ON locations.id = items.location_id
GROUP BY locations.id, locations.name
) location_data
INNER JOIN (
SELECT locations.id, photo
FROM locations
) photo_data ON location_data.id = photo_data.id
ORDER BY name ASC