使用LEFT JOIN的表上的COUNT行数在不存在时返回1

时间:2016-02-07 14:15:24

标签: php sql left-join

我有两张桌子,例如:

发表

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

但结果是一样的。怎么做?

2 个答案:

答案 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。