Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get the highest amount of a value in a mysql database?

I want to display the user with the most posts. the posts are added by counting how many times their username is displayed in the database. How can I grab all the elements and check to see which value appears more then others?

So say my database looks like this:

id | username
1 | test
2 | test
3 | no test

"test" is shown the most, so how could I say

highest poster: "test"
like image 293
Dennis Avatar asked Jan 28 '26 16:01

Dennis


2 Answers

This query returns username and number of occurrences, sorted in reverse order, so the first record is the one with more occurrences:

select username, count(id) from tablename 
group by username
order by count(id) desc

UPDATE: As pointed by thedugas and Joe Phillips, you can add a limit 1 clause to this query to get only the record with the highest number of occurrences

like image 100
deluan Avatar answered Jan 30 '26 09:01

deluan


select username, count(id) as uc
from tableName
group by username
order by uc desc
limit 1
like image 34
dugas Avatar answered Jan 30 '26 08:01

dugas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!