MySQL计数,分组依据和连接查询

时间:2014-12-28 14:50:29

标签: mysql sql join count group-by

我有两个表:userscomments,其中每个评论都属于一个用户。

用户

id  user  class
1   mike    A
2   joe     B
3   john    A

评论

id  user_id    comment
1     1      "some text"
2     2      "some text"
3     1      "some text"
4     2      "some text"
5     3      "some text"
6     2      "some text"
7     2      "some text"

我希望计算每个用户类中的评论数量。 结果应该是:

A 3
B 4

我试过这个:

SELECT users.class, count(*) AS count 
  FROM comments 
 GROUP BY comments.user_id.class
 ORDER BY count DESC;

但不起作用。

2 个答案:

答案 0 :(得分:1)

您需要像这样进行加入

Select u.class, count(*) 
From users u
Join comments c on c.user_id = u.id
Group by u.class

答案 1 :(得分:1)

您应该JOIN两个表ON每个组的ID:

SELECT u.`class`
     , count(*) AS `count` 
FROM `comments` c JOIN `users` u  ON u.`id` = c.`user_id` 
GROUP BY u.`class`
ORDER BY `count` DESC;