For example, in a table I have created called 'likes', there are three fields: id (irrelevant), user id (the id of the user), and post id (the id of the post). Say I have numerous records and I want to find out which post id is in the database the most number of times. To be clear, I am not asking which record has the biggest number in the post id field. Rather, I'm looking for which post id is listed the most times. For example, let's say one post id (222) is in the database 7 times while every other post id has been used 1 time each. I need to find the post id of 222 in this case. If possible how could I find the top 5 post id's with the highest amount of uses within the records?
Asked
Active
Viewed 94 times
1 Answers
1
It's a fairly simple aggregate function count()
that will count the number of matching records.
select
postID,
count(*) as numLikes
from
yourTable
group by
postID
order by
numLikes desc
This will list the posts in order of the number of times they were liked.
Additionally, as I am providing you mainly a solution, you would do really well to read this Q&A that I wrote which will explain in a lot more detail how this all works - in fact I do a fair bit to cover off aggregate functions like this in it. I explain exactly what is going on in this sort of query around halfway down the first answer to the question :)
-
Now, why did I read that in a Mortal Combat "Flawless Victory!" voice in my head... – Fluffeh Sep 18 '13 at 01:16