簡體   English   中英

選擇多個最大值

[英]selecting multiple max values

我在mysql數據庫上有這樣的表:

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

我希望結果是具有最高Item值的3條記錄

select max(item)僅返回1個值如何選擇多個最大值? 謝謝

您可以使用派生表獲取最大值,然后join其聯接回原始表以查看與其對應的所有行。

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

編輯:

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

如果您使用不帶GROUP BY的“聚合函數”,則僅返回一行。

您可以將GROUP BY與聚合函數一起使用。

這是SQLFiddle演示

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

希望這可以幫助。

有圖形說明 有腳本mysql(低抽象級別,沒有內部聯接或某物)

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" 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM