Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Find the total amount of posts per user

Tags:

sql

mysql

I have a Database with the following two tables, USERS, POSTS I am looking for a way to get the count of how many posts a user has.

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

I have tried many variations of the following SQL command with out any success. instead of showing the count of posts for a single user it shows a single row with all the posts as the count.

SELECT users.* , COUNT( Posts.user_id ) 
FROM users
LEFT JOIN Posts ON users.id = Posts.user_id

In the end I want something like this

+----+------+ 
| ID | Count|
+----+------+
| 1  |  2   |  
+----+------+
| 2  |  1   |  
+----+------+
like image 864
Steven Smethurst Avatar asked Feb 03 '10 23:02

Steven Smethurst


2 Answers

Figured it out. Smacks self in head

SELECT users.*, count( posts.user_id ) 
FROM posts LEFT JOIN users ON users.id=posts.user_id 
GROUP BY posts.user_id
like image 71
Steven Smethurst Avatar answered Sep 21 '22 11:09

Steven Smethurst


select users.*, count(posts.user_id)

from users, posts
where users.user_id = posts.user_id
group by posts.user_id

But the best way is too add a field to the users table and keep the amount of posts made by each users, and updated it whenever a post is created or deleted. Otherwise, you'll slow down your DB when it grows bigger.

like image 45
iBiryukov Avatar answered Sep 21 '22 11:09

iBiryukov