[英]MySQL ORDER BY total rows of user in another table
Suppose, I want to show a list of users ordering by the most number of messages they have sent. 假设我想显示一个按用户发送的邮件数量排序的用户列表。
I have 2 tables: Users
and Messages
我有2个表格:
Users
和Messages
I have 10 users 我有10位使用者
User A sent 20 messages (have 20 rows in Messages table) 用户A发送了20条消息(“消息”表中有20行)
SELECT * FROM messages WHERE user='A'
User B sent 17 msgs
User C sent 19
User D sent 13
and so on. 等等。
I want to a query that will list Users in order of their total messages sent. 我想要一个查询,该查询将按发送的邮件总数列出用户。 Like:
喜欢:
1. A (20 msgs)
2. C (19 msgs)
3. B (17 msgs)
4. D (13 msgs)
I tried hard but I can't find any query to execute this. 我尽力了,但找不到任何查询来执行此操作。 Please help.
请帮忙。 Thanks in advance.
提前致谢。
SELECT user, COUNT(*) FROM messages GROUP BY user ORDER BY count(*) DESC;
如果要打印名称加入用户表,
select user_name, count(*) from users inner join messages m on users.userid=m.messageid group by userid order by count(*) desc;
You can sort using an alias
: 您可以使用
alias
进行排序:
SELECT user, COUNT(1) as cnt
FROM Messages
GROUP BY user
ORDER BY cnt DESC;
or position
: 或
position
:
SELECT user, COUNT(1) as cnt
FROM Messages
GROUP BY user
ORDER BY 2 DESC;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.