MySQL QUERY查找每个用户的帖子数量

时间:2016-11-09 12:42:37

标签: mysql sql

我有一个包含以下两个表的数据库,USERS,POSTS我正在寻找一种方法来计算用户有多少帖子(postCount),以及用户是否有任何帖子postCount将等于零

 Users            Posts
 +----+------+    +----+---------+-----------+
 | ID | Name |    | ID | user_id | Name      |
 +----+------+    +----+---------+-----------+
 | 1  | Bob  |    | 1  | 1       | Blargg... | 
 | 2  | Jim  |    | 2  | 1       | Blargg... | 
 | 3  | Jo   |    | 3  | 2       | Blargg... | 
 +----+------+    +----+---------+-----------+

最后我想要这样的事情:

 +----+------+ 
 | ID | Count|
 +----+------+
 | 1  |  2   |  
 | 2  |  1   |  
 | 3  |  0   |  
 +----+------+

4 个答案:

答案 0 :(得分:4)

试试这个:

SELECT u.ID, u.Name, COUNT(p.Name)
FROM Users AS u
LEFT JOIN Posts AS p ON u.ID = p.user_id
GROUP BY u.ID, u.Name

答案 1 :(得分:0)

SELECT t1.ID, COUNT(*) AS `Count`
FROM Users t1
LEFT JOIN Posts t2
    ON t1.ID = t2.user_id
GROUP BY t1.Id

答案 2 :(得分:0)

select
u.id,
count(p.id)
from users u
left join posts p on p.user_id = u.id
group by u.id
order by u.id

答案 3 :(得分:0)

你应该加入这两个表,以便包括来自users的所有条目,即使没有用户的帖子,然后是一个简单的order by和一个聚合函数来计算帖子:

select users.id, count(posts.id) from users left join posts on users.id = posts.user_id group by posts.user_id