Skip to content Skip to sidebar Skip to footer

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 I have 10 users User A sent 20 messages (have 20

Solution 1:

SELECT user, COUNT(*) FROM messages GROUP BY user ORDER BY count(*) DESC;

Solution 2:

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;

Solution 3:

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;

Post a Comment for "Mysql Order By Total Rows Of User In Another Table"