简体   繁体   中英

selecting multiple max values

i have a table like this on a mysql database:

id | item
-----------
1  | 2
2  | 2
3  | 4
4  | 5
5  | 8
6  | 8
7  | 8

i want the result to be 3 record with the highest Item value

select max(item) returns only 1 value how can i select multiple max values? thank you

You can use a derived table to get the maximum value and join it back to the original table to see all rows corresponding to it.

select t.id, t.item 
from tablename t
join (select max(item) as mxitem from tablename) x
on x.mxitem = t.item

Edit:

select t.co_travelers_id, t.booking_id, t.accounts_id 
from a_co_travelers t
join (select accounts_id, max(booking_id) as mxitem 
      from a_co_travelers
      group by accounts_id) x 
on x.mxitem = t.booking_id and t.accounts_id = x.accounts_id

If you use an 'aggregate function' without GROUP BY only one row will be returned.

You may use GROUP BY , with aggregate functions.

Here is SQLFiddle Demo

SELECT id,max(item) AS item 
 FROM table_name
 GROUP BY id 
 ORDER BY item DESC 
 LIMIT 3

Hope this helps.

There is the graphical explanation . There is script mysql (low abstraction level, no inner join or sth)

select * from ocena, uczen where ocena.ocena = (SELECT MAX(ocena.ocena) FROM ocena WHERE ocena.przedmiot_id="4" and ocena.uczen_id="1") and ocena.uczen_id=uczen.id and ocena.przedmiot_id="4" and uczen_id="1" 

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