我有两张桌子:
我想让所有按SUM订购的用户出现在Rooms表中(例如,users.id = rooms.uid)。此外,我想知道每个人在那里多少次。
例如:
Solomon - 5
Igor - 3
Thomas - 1
John - 0
Total: 9
这样做的正确查询是什么?
答案 0 :(得分:1)
SELECT a.id, a.first_name, a.last_name, a.share,
COUNT(b.uid) TotalVisits
FROM users a
LEFT JOIN visits b
ON a.id = b.uid
GROUP BY a.id, a.first_name, a.last_name, a.share
ORDER BY TotalVisits DESC
这很有用!
答案 1 :(得分:0)
这有点复杂,三个重要的SQL组件:left join
,group by
和rollup
:
select u.uid, count(r.uid) as cnt
from users u left join
rooms r
on u.uid = r.uid
group by u.uid with rollup
order by (case when u.uid is not null then cnt desc else -1 end);