我有两个表:users
和comments
,其中每个评论都属于一个用户。
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;
但不起作用。
答案 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;