我有两张桌子:
users
:
id | name
-----------
1 | user 1
2 | user 2
3 | user 3
和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
我需要检索按频率排序的users
,例如:
id | name | posts
-------------------
2 | user 2 | 4
1 | user 1 | 1
3 | user 3 | 0
有些用户可能没有帖子!
目前我有2个查询,分3步执行:
userId
php
加入上述问题
以上是否可以在单个sql查询中进行?
答案 0 :(得分:3)
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
答案 1 :(得分:1)
另一个版本,它阻止在group by子句中列出users
表中的所有字段。在许多情况下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