我有两张桌子,例如:
发表:
id | author | content | date
1 | Lucas | Hello! | 2016
2 | Igor | Hi! | 2016
注释:
id | post_id | content | date
1 | 2 | hehehe | 2016
2 | 1 | hahaha | 2016
3 | 2 | huhuhu | 2016
我要SELECT
使用COUNT
返回所有帖子以及所有评论的post.id = comment.id
行。
所以,我试过了:
SELECT p.id, p.author, p.content, p.date, COUNT(*) AS numComments FROM post p LEFT JOIN comment ON p.id = post_id WHERE p.author = '$author' GROUP BY p.id DESC LIMIT 12
我做到了。但是,即使没有p.id = post_id
的评论,他也会返回1。
所以,我试过了:
SELECT p.id, p.author, p.content, p.date, CASE WHEN COUNT(*) < 1 THEN '0' ELSE COUNT(*) END AS numComments FROM post p LEFT JOIN comment ON p.id = post_id WHERE p.author = '$author' GROUP BY p.id DESC LIMIT 12
但结果是一样的。怎么做?
答案 0 :(得分:1)
你可以通过这种方式获得数量,也可以通过以下方式排序:
SELECT p.id, p.author, p.content, p.date,
(select COUNT(*) from comment where p.id = comment.post_id) AS numComments FROM post p
WHERE p.author = '$author'
ORDER BY p.id DESC LIMIT 12
答案 1 :(得分:1)
由于外部联接返回一行,即使没有匹配的数据,您需要从内部表中计算一列,通常它是连接中使用的列:
SELECT p.id, p.author, p.content, p.date, COUNT(post_id) AS numComments
FROM post p LEFT JOIN comment ON p.id = post_id
WHERE p.author = '$author'
GROUP BY p.id -- seems to be mysql, otherwise you need to add more columns to the list
如果您不想显示零计数的行,只需切换到 INNER JOIN。