Reputation: 4482
So I have a bunch of messages with a "room" column. What I want to do is find the top 5 rooms by number of messages. So if 1000 messages in the last 5 days are from room A and 500 are from room B, and so on I will be returned results in the form A, B, C, D, E.
I figured out how to find all of the "rooms" for the last 5 days
SELECT room
FROM messages
WHERE
timestamp < (SELECT UNIX_TIMESTAMP()*1000)
AND
timestamp > (SELECT UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 5 day))*1000);
But when I try to simply add ORDER BY count(room);
to the end the entire list gets flattened into a single irrelevant result (the most recent message).
What am I missing?
Upvotes: 1
Views: 664
Reputation: 9853
As mentioned in the comment by M Khalid Junaid : group by
the room
column and then order by:
SELECT room,count(*)
FROM messages
WHERE
timestamp < (SELECT UNIX_TIMESTAMP()*1000)
AND
timestamp > (SELECT UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 5 day))*1000)
group by room
order by 2 desc
limit 5;
Upvotes: 2