tags:

views:

40

answers:

2

Hello

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   |  
+----+------+
+1  A: 

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
Steven smethurst
A: 
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.

Ilya Biryukov
Without a lefft join...you'll exclude all users without a post.
Nick Craver