假设,我想显示按用户发送的大量邮件排序的用户列表。
我有2个表:Users
和Messages
我有10个用户
用户A发送了20条消息(在消息表中有20行)
SELECT * FROM messages WHERE user='A'
User B sent 17 msgs
User C sent 19
User D sent 13
等等。
我想要一个查询,按照发送的总消息顺序列出用户。像:
1. A (20 msgs)
2. C (19 msgs)
3. B (17 msgs)
4. D (13 msgs)
我努力但我找不到任何查询来执行此操作。请帮忙。提前谢谢。
答案 0 :(得分:4)
SELECT user, COUNT(*) FROM messages GROUP BY user ORDER BY count(*) DESC;
答案 1 :(得分:0)
如果要打印名称加入用户表,
select user_name, count(*) from users inner join messages m on users.userid=m.messageid group by userid order by count(*) desc;
答案 2 :(得分:0)
您可以使用alias
:
SELECT user, COUNT(1) as cnt
FROM Messages
GROUP BY user
ORDER BY cnt DESC;
或position
:
SELECT user, COUNT(1) as cnt
FROM Messages
GROUP BY user
ORDER BY 2 DESC;