所以我有这张专辑和图片表。图像有一个名为album_id
的列,它会获取它们所在的相册ID。到目前为止一切都很好。
现在我需要从Albums表中选择信息,我还需要每个专辑行的图像数量。我尝试使用LEFT JOIN
和COUNT(*)
,但它只返回一行,这对我的情况来说非常低效。
这是我正在使用的原始查询,它不会返回与计数相关的任何内容:
SELECT album_id, album_name, album_preview, album_owner, album_time, album_access
FROM imgzer_albums WHERE album_owner = SOME_VALUE
这是LEFT JOIN
的查询:
SELECT a.album_id, a.album_name, a.album_preview, a.album_owner, a.album_time, a.album_access, COUNT(i.*) AS images
FROM imgzer_albums a
LEFT JOIN imgzer_images i
ON a.album_id = i.album_id
WHERE album_owner = SOME_VALUE
如何计算每个相应相册ID的图像数量而不仅限于一个结果?
答案 0 :(得分:0)
试试这个
SELECT a.album_id, a.album_name, a.album_preview, a.album_owner, a.album_time, a.album_access, COUNT(i.*) AS images
FROM imgzer_albums a
LEFT JOIN imgzer_images i
ON a.album_id = i.album_id
WHERE album_owner = SOME_VALUE
GROUP BY a.album_id
答案 1 :(得分:0)
没有分组的解决方案是相关查询:
SELECT a.album_id, a.album_name, a.album_preview, a.album_owner, a.album_time, a.album_access,
(select COUNT(*) from imgzer_images i where a.album_id = i.album_id) AS images
FROM imgzer_albums a
WHERE album_owner = SOME_VALUE