简体   繁体   中英

How to get the latest Data with WHERE and MAX in MySQL

This is my current MySQL Table:

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

I want to query all 'Crops' with their 'Price' as latest in the area name 'Cogon' . This is the last query that I used:

SELECT ID, Crop, Area, MAX( DateUpdated ) 
AS Latest, DateUpdated, Price 
FROM crops 
WHERE Area = TRIM( 'Cogon' ) 
GROUP BY Area, Crop;

In which I want to get all crops in 'Cogon' with their latest prices.

Well the syntax above outputs all the crops in 'Cogon'. However, it does not output the latest Price of Onion (ID 14) but instead outputs the older data (ID 9).

What if you say like

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

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