我有两个表如何计算的意见,而选择职位
tb_postsid,title,description
tb_commentsid,post_id,comment
我想选择与评论计数的所有帖子。
如何为它写单个查询?
我有两个表如何计算的意见,而选择职位
tb_postsid,title,description
tb_commentsid,post_id,comment
我想选择与评论计数的所有帖子。
如何为它写单个查询?
我认为这应该这样做:
SELECT tb_posts.id, tb_posts.title, tb_posts.description
FROM tb_posts INNER JOIN tb_comments
ON tb_posts.id = tb_comments.post_id
GROUP BY tb_posts.id, tb_posts.title, tb_posts.description
HAVING COUNT(*) > SOME_THRESHOLD_VALUE
SELECT a.id,a.title,a.description, count(b.id) FROM tb_posts a, tb_comments b,
WHERE a.id=b.post_id;
如果只有tb_comments具有post_id,则为选择行。如果帖子没有评论,然后?? – w3father
如果帖子没有评论,那么'count'值将为0 – Balanivash
试试这个,
SELECT tb_posts.title, COUNT(tb_comments.id)
FROM tb_comments LEFT JOIN tb_posts ON tb_posts.id = tb_comments.post_id
GROUP BY tb_comments.post_id, tb_posts.title
我得到了解决
SELECT p.id,p.title,p.description,c.cm FROM tb_posts AS p LEFT JOIN
(SELECT post_id,count(id) as cm FROM `tb_comments` GROUP BY post_id) AS c
ON p.id = c.post_id
我不认为这个查询返回的意见的计对于每个帖子.. – Balanivash
是的,但它限制了结果对那些有一定数量的人来说,这就是要求。将COUNT(tb_comments.id)'添加到select语句中包括计数。 – faester
你好...我认为OP没有那么清楚,“有评论”或者意味着基于评论或者结果表应该有评论数。 – Balanivash