简体   繁体   English

如何在MySQL中记录最后日期?

[英]How take record with last date in MySQL?

In MySQL database I have table with such structure: 在MySQL数据库中,我的表具有以下结构:

| OBJECT_ID | OBJECT_NAME | TIME_KEY            | OBJECT_CODE |
|-------------------------------------------------------------|
| 66        | Kemir       | 2019-01-01 12:00:00 | XVG         |
| 66        | Kemir       | 2019-01-01 13:00:00 | GTG         |
| 88        | Damir       | 2019-01-01 12:00:00 | NGD         |
| 99        | Vivle       | 2019-01-01 12:00:00 | FGT         |
| 99        | Vivle       | 2019-01-01 12:00:00 | HFD         |
| 99        | Vivle       | 2019-01-01 14:00:00 | KJD         |

In final result I need to take all data with last date as below: 在最终结果中,我需要获取截止日期如下的所有数据:

| OBJECT_ID | OBJECT_NAME | TIME_KEY            | OBJECT_CODE |
|-------------------------------------------------------------|
| 66        | Kemir       | 2019-01-01 13:00:00 | GTG         |
| 88        | Damir       | 2019-01-01 12:00:00 | NGD         |
| 99        | Vivle       | 2019-01-01 14:00:00 | KJD         |

I use next SQL statement: 我使用下一条SQL语句:

SELECT *
FROM TABLE_MAIN
GROUP BY OBJECT_ID DESC;

It return first date of the records: 它返回记录的第一个日期:

| OBJECT_ID | OBJECT_NAME | TIME_KEY            | OBJECT_CODE |
|-------------------------------------------------------------|
| 66        | Kemir       | 2019-01-01 12:00:00 | XVG         |
| 88        | Damir       | 2019-01-01 12:00:00 | NGD         |
| 99        | Vivle       | 2019-01-01 12:00:00 | FGT         |

How to fix this problem? 如何解决这个问题?

Try following query: 尝试以下查询:

Select *from
table1 t1
where 
   (object_id,time_key) in 
           (select object_id, max(time_key)
            from table1
            group by object_id)
 ;

You could use a correlated subquery 您可以使用相关子查询

select t1.* form TABLE_MAIN t1
  where t1.TIME_KEY= (
                select max(TIME_KEY) 
         from TABLE_MAIN t2 where t1.OBJECT_ID=t2.OBJECT_ID
        and   t1.OBJECT_NAME=t2.OBJECT_NAME
      )

You want to filter the rows, so use WHERE . 您想过滤行,所以使用WHERE Here is one method: 这是一种方法:

SELECT m.*
FROM TABLE_MAIN m
WHERE m.time_key = (SELECT MAX(m2.time_key)
                    FROM TABLE_MAIN m2
                    WHERE m2.object_id = m.object_id
                   );

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

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