我有一张图片
id | url | albumID
------------------
1 | null | 1
2 | null | 1
3 | null | 2
4 | null | 5
和评论表
id | text | imageID
------------------
1 | 'xD' | 1
2 | ':)' | 1
3 | ':P' | 1
4 | '(_!_)' | 2
我想获得所有带有albumID = 1的图片和带有与之前结果匹配的imageID的评论数。
SELECT images.id, COUNT(comments.imageID) AS comments FROM images
LEFT JOIN comments ON comments.imageID=images.id
WHERE images.albumID=1
我得到了:
id | comments
------------------
1 | 3
没关系,但是当我尝试搜索不存在的albumID的图像时:
SELECT images.id, COUNT(comments.imageID) AS comments FROM images
LEFT JOIN comments ON comments.imageID=images.id
WHERE images.albumID=3
我得到了:
id | comments
------------------
null | 0
我不希望得到null的结果。那我的查询有什么问题?
修改
解决方案1
来自@cdaiga和@isaace,谢谢你
SELECT images.id, COUNT(comments.imageID) AS comments FROM images
LEFT JOIN comments ON comments.imageID=images.id
WHERE images.albumID=3
GROUP BY images.id;
解决方案2
在思考之后,我自己,但我不确定这个解决方案的性能如何SELECT images.id,
(
SELECT COUNT(*) FROM comments WHERE comments.imageID=images.id
) AS comment FROM images
WHERE images.albumID=3
答案 0 :(得分:2)
通常在您运行时:
SELECT images.id FROM images
LEFT JOIN comments ON comments.imageID=images.id
WHERE images.albumID=3;
结果是空集。 但是跑步:
SELECT images.id, COUNT(comments.imageID) AS comments FROM images
LEFT JOIN comments ON comments.imageID=images.id
WHERE images.albumID=3;
返回null,计数为零,因为count不用作聚合函数。要获得正确的结果,您必须通过添加group by子句将count用作聚合函数。
SELECT images.id, COUNT(comments.imageID) AS comments FROM images
LEFT JOIN comments ON comments.imageID=images.id
WHERE images.albumID=3
GROUP BY images.id;
答案 1 :(得分:2)
通常在您运行时:
SELECT images.id FROM images
LEFT JOIN comments ON comments.imageID=images.id
WHERE images.albumID=3;
结果是空集。 但是跑步:
SELECT images.id, COUNT(comments.imageID) AS comments FROM images
LEFT JOIN comments ON comments.imageID=images.id
WHERE images.albumID=3;
返回null,计数为零,因为count不与聚合一起使用。要获得正确的结果,您必须通过添加group by子句将count用作聚合函数。
SELECT images.id, COUNT(comments.imageID) AS comments FROM images
LEFT JOIN comments ON comments.imageID=images.id
WHERE images.albumID=3
GROUP BY images.id;
答案 2 :(得分:2)
如果您添加GROUP BY
,则应该修复它。
SELECT images.id, COUNT(comments.imageID) AS comments FROM images
LEFT JOIN comments ON comments.imageID=images.id
WHERE images.albumID=3
GROUP BY images.id
在mysql
的更高版本中,如果没有GROUP BY
,您将无法运行查询。