Mysql按日期获取每个特定组的最近行

时间:2016-07-01 17:34:36

标签: mysql database

我有桌子(afk_map_data):

id map_id state_id measures_id value created_date

问题是>>我想通过最近的created_date

仅获取measures_id值的最新行

我尝试了很多解决方案我尝试了很多东西但它很愚蠢,我发布这个选择语句是我的问题清楚

 SELECT  md.id,md.measures_id,md.value,md.created_date FROM afk_map_data md     
 WHERE  
 md.map_id = 1 
 AND md.state_id = 2
 AND md.measures_id = 4  


the result was :

id   measures_id    value  created_date
1           4        777    2016-07-03  
2           4        888    2016-07-03
3           4        999    2016-07-02
4           4        555    2016-07-02

the result that i want is : 

id   measures_id    value  created_date
1           4        777    2016-07-03  
2           4        888    2016-07-03

Thanks a lot ..

1 个答案:

答案 0 :(得分:0)

在日期列

上使用 MAX条件
 Select TT.id,T.measures_id,TT.value,T.d from afk_map_data TT
        INNER JOIN (
        SELECT  measures_id,MAX(created_date)d FROM afk_map_data
        GROUP BY measures_id )T
        ON  T.d = TT.created_date
WHERE  
 TT.map_id = 1 
 AND TT.state_id = 2
 AND TT.measures_id = 4