我对一个愚蠢的查询有点困惑:
我从表作者和表格评论加入表帖子的行,方式如下:
SELECT posts.*, authors.name, COUNT(comments.id_post) AS num_comments
FROM posts JOIN authors ON posts.id_author = authors.id_author
LEFT JOIN comments ON posts.id_post = comments.id_post
WHERE posts.active = 1
AND comments.active = 1
当然,这不起作用。
我尝试做的是检索:
1)我所有的活动帖子(未标记为已删除的帖子);
2)作者姓名;
3)每个帖子的活动评论数量(未标记为删除的评论数量)(如果至少有一个);
有什么办法?我知道这是一个微不足道的,但到现在为止我的大脑越位了...... 谢谢!
答案 0 :(得分:1)
据推测,id_post
唯一标识posts
中的每一行。试试这个:
SELECT p.*, a.name, COUNT(c.id_post) AS num_comments
FROM posts p JOIN
authors a
ON p.id_author = a.id_author LEFT JOIN
comments c
ON p.id_post = c.id_post
WHERE p.active = 1 AND c.active = 1
GROUP BY p.id_post;
请注意,这使用MySQL扩展。在大多数其他数据库中,您需要在posts
子句中列出a.name
加group by
中的所有列。
编辑:
以上内容基于您的查询。如果您希望所有活动帖子都有活跃评论,请执行以下操作:
SELECT p.*, a.name, SUM(c.active = 1) AS num_comments
FROM posts p LEFT JOIN
authors a
ON p.id_author = a.id_author LEFT JOIN
comments c
ON p.id_post = c.id_post
WHERE p.active = 1
GROUP BY p.id_post;
答案 1 :(得分:0)
由于你正在计算,你需要有一个分组。所以你需要添加
Group By posts.*, authors.name
答案 2 :(得分:0)
你应该将GROUP BY子句与聚合函数一起使用。尝试类似的事情:
SELECT posts.*, authors.name, COUNT(comments.id_post) AS num_comments
FROM posts JOIN authors ON posts.id_author = authors.id_author
LEFT JOIN comments ON posts.id_post = comments.id_post
-- group by
GROUP BY posts.*, authors.name
--
WHERE posts.active = 1
AND comments.active = 1
答案 3 :(得分:0)
我找到了正确的解决方案:
SELECT posts.id_post, authors.name, COUNT(comments.id_post) AS num_comments
FROM posts JOIN authors
ON posts.id_author = authors.id_author
LEFT OUTER JOIN comments
ON (posts.id_post = comments.id_post AND comments.active = 1)
WHERE posts.active = 1
GROUP BY posts.id_post;
感谢大家的帮助!