简体   繁体   中英

How to find the highest number of times a value is in records?

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?

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM