简体   繁体   English

如何在MySQL中使用WHERE和MAX获取最新数据

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

This is my current MySQL Table: 这是我当前的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

I want to query all 'Crops' with their 'Price' as latest in the area name 'Cogon' . 我想用区域名称'Cogon'中的最新'Price'查询所有'Crops' '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. 我想在其中以最新价格获得'Cogon'中的所有农作物。

Well the syntax above outputs all the crops in 'Cogon'. 好吧,以上语法在“ Cogon”中输出所有农作物。 However, it does not output the latest Price of Onion (ID 14) but instead outputs the older data (ID 9). 但是,它不会输出最新的洋葱价格(ID 14),而是输出较旧的数据(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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM