MySQL ORDER BY total rows of user in another table

后端 未结 3 851
借酒劲吻你
借酒劲吻你 2021-01-28 15:37

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

I h

相关标签:
3条回答
  • 2021-01-28 16:02

    You can sort using an alias:

    SELECT user, COUNT(1) as cnt
    FROM Messages 
    GROUP BY user 
    ORDER BY cnt DESC;
    

    or position:

    SELECT user, COUNT(1) as cnt
    FROM Messages 
    GROUP BY user 
    ORDER BY 2 DESC;
    
    0 讨论(0)
  • 2021-01-28 16:15

    if you want to print the names join users table,

    select user_name, count(*) from users inner join messages m on users.userid=m.messageid group by userid order by count(*) desc;
    
    0 讨论(0)
  • 2021-01-28 16:19
    SELECT user, COUNT(*) FROM messages GROUP BY user ORDER BY count(*) DESC;
    
    0 讨论(0)
提交回复
热议问题