带有count的mysql查询

时间:2012-05-31 12:37:34

标签: mysql sql subquery

我遇到了自己的MySQL查询技能限制,所以我希望一些SQL大师可以帮助解决这个问题。我有2张桌子:

Table "comments" 
comment_ID    | comment_post_ID
     120      |    620
     121      |    620
     122      |    620
   Table "comments_like"
like_ID     |  comment_ID
    1       |   120
    2       |   120

我将通过comment_post_ID得出具有相同组的评论数量:

COUNT(comments in comments like) | comment_post_ID
      1                          |     620

4 个答案:

答案 0 :(得分:0)

我猜这个子查询最简单:

SELECT (SELECT COUNT(like_ID) FROM `comments_like` cl WHERE cl.comment_ID=c.comment_ID) AS comments_in_comments_like, c.comment_post_ID FROM `comments` c

由于评论ID 120在您的示例中有2个喜欢

,因此对于喜欢这将产生2的计数

答案 1 :(得分:0)

此查询在comment_like表

中为其注释提供post_id和no
 SELECT comment_post_ID, count(like_ID)
 from (select distinct comment_post_ID,like_ID 
       from comments_like cl , comments c
 where cl.comment_ID= c.comment_ID ) as iq
 group by comment_post_ID

答案 2 :(得分:0)

select cmtLike.like_ID, commnts.comment_post_ID
from comments_like cmtLike left join comments commnts on cmtLike.comment_ID = commnts.comment_ID

答案 3 :(得分:0)

如果您只需要计算一次comments_like中列出的每条评论,那么:

select comment_post_ID, count(distinct cl.comment_ID) 
from comments c, comments_like cl 
where c.comment_id = cl.comment_id 
group by comment_post_ID