Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In SQL, how do I get the row with the maximum value for a particular column?

Tags:

sql

mysql

I have a query:

SELECT COUNT(*) as votes, a.member_id 
FROM ballots a
WHERE ballot_id = 1
GROUP BY a.member_id

which yields something like:

votes  member_id
1      paul
5      mike
3      noynoy
10     andy
2      noel

I'd like to be able to get the row "andy" because he got the highest "votes".

How do I change my query to do this?

Thanks in advance for your help :)

like image 395
Obay Avatar asked Dec 17 '22 03:12

Obay


1 Answers

You can order it from highest to lowest votes using ORDER BY and then DESC for descending order. Then LIMIT the results to only one row (i.e. the highest).

SELECT COUNT(*) as votes, a.member_id 
FROM ballots a
WHERE ballot_id = 1
GROUP BY a.member_id
ORDER BY votes DESC
LIMIT 1
like image 153
Rich Adams Avatar answered Apr 08 '23 05:04

Rich Adams