[英]How to count entries specifically matching another row in join
我一直在尝试进行SQL查询,以显示每个帖子的评论数。 问题是,我一直尝试添加到的查询已经有一个LEFT JOIN。 到目前为止,我已经成功地使它显示了一个帖子(尽管是一个错误的帖子)以及整个表中带有以下查询的评论总数:
SELECT
*,
Count(tbl_comments.comm_id) as CommentCount
FROM
tbl_posts
LEFT JOIN tbl_users ON tbl_posts.author = tbl_users.id
LEFT JOIN tbl_comments ON tbl_posts.post_id = tbl_comments.comm_id
WHERE
tbl_users.role >= 3
ORDER BY
tbl_posts.post_time DESC
LIMIT
1
在对“计数”部分进行注释的情况下,查询将返回最新的帖子。 否则,它将返回数据库中的第一条帖子,以及整个表中的注释总数。 我将如何显示正确(最新)的帖子以及仅对该帖子发表的评论? 评论表有一个“父”字段,我在其中存储发表评论的帖子的ID,但是我无法弄清楚在查询中指定哪个位置。 提前致谢。
如果您想要每个帖子的评论数。 您需要GROUP BY
SELECT
tbl_posts.post_id,
Count(tbl_comments.comm_id) as CommentCount
FROM
tbl_posts
INNER JOIN tbl_users
ON tbl_posts.author = tbl_users.id
LEFT JOIN tbl_comments
ON tbl_posts.post_id = tbl_comments.comm_id
WHERE
tbl_users.role >= 3
GROUP BY tbl_posts.post_id
注意:此加入条件看起来很奇怪
ON tbl_posts.post_id = tbl_comments.comm_id
应该:
ON tbl_posts.post_id = tbl_comments.post_id
我的猜测comm_id
是评论的PK,而不是FK。
我会使用来自post.id
的group_by
,然后对每个帖子进行count(tbl.comments.id)
。 这样,您可以为每个帖子获取与单个帖子相关联的不同评论数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.