[英]How to get the latest Data with WHERE and MAX in MySQL
這是我當前的MySQL表:
Crop ID Price DateUpdated Area
Okra 4 50 2014-02-05 21:42:26 Bulua
Eggplant 5 20 2014-02-05 21:42:26 Lapasan
Okra 6 35 2014-02-05 21:42:26 Agora
Cauliflower 8 300 2014-02-05 21:42:26 Patag
Onion 9 10 2014-02-05 22:02:34 Cogon
Kalabasa 10 50 2014-02-05 22:59:30 Cogon
Garlic 11 130 2014-02-05 22:59:44 Cogon
Onion 14 34.4 2014-02-05 23:12:21 Cogon
Onion 15 54 2014-02-07 02:40:13 Cogon
我想用區域名稱'Cogon'
中的最新'Price'
查詢所有'Crops'
'Cogon'
。 這是我使用的最后一個查詢:
SELECT ID, Crop, Area, MAX( DateUpdated )
AS Latest, DateUpdated, Price
FROM crops
WHERE Area = TRIM( 'Cogon' )
GROUP BY Area, Crop;
我想在其中以最新價格獲得'Cogon'中的所有農作物。
好吧,以上語法在“ Cogon”中輸出所有農作物。 但是,它不會輸出最新的洋蔥價格(ID 14),而是輸出較舊的數據(ID 9)。
如果你說喜歡
SELECT Crop,
Area,
DateUpdated,
Price
FROM crops cr
WHERE trim(Area) = 'Cogon'
and
DateUpdated = (select max(DateUpdated)
from crops
where Crop = cr.Crop and trim(Area) = 'Cogon' ) ;
您想按日期更新ORDER BY DateUpdated DESC
或按ORDER BY ID DESC
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.