table 上的 COUNT 行数与 LEFT JOIN returns 1 当不存在时

COUNT number of rows on table with LEFT JOIN returns 1 when not exists

我有两个表,例如:

post:

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 return 所有 post 和 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 he returns 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

但是结果是一样的。如何做到这一点?

可以这样算,最后是order by not group by:

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

作为外部联接 return 一行,即使没有匹配的数据,您也需要从 内部 table 计算一列,通常是该列用于加入:

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

如果您不想显示计数为零的行,只需切换到 内连接。