Reputation: 12579
I have 2 tables:
users
:
id | name
-----------
1 | user 1
2 | user 2
3 | user 3
and posts
:
id | userId | text
--------------------
1 | 1 | text 1
2 | 1 | text 2
3 | 2 | text 3
4 | 2 | text 4
5 | 2 | text 5
6 | 2 | text 6
I need to retrieve users
ordered by post-frequency, e.g.:
id | name | posts
-------------------
2 | user 2 | 4
1 | user 1 | 1
3 | user 3 | 0
Some users might not have posts!
Currently I have 2 queries and doing it in 3 steps:
userId
php
to join the aboveQuestion
Is the above possible to do in a single sql query?
Upvotes: 0
Views: 69
Reputation: 33381
Another version, which prevents listing all fields from users
table in group by clause. Also more fast in many cases IMO.
select u.id, u.name, coalesce(c.cnt, 0) as posts
from users u
left join
(select userId, couint(*) cnt from posts group by userId) c
on u.id = c.userId
Upvotes: 1
Reputation: 204756
select u.id, u.name, count(p.id) as posts
from users u
left join posts p on p.userid = u.id
group by u.id, u.name
order by posts desc
Upvotes: 3