MySQL 选择具有给定 ID 的最后查询

MySQL selecting the last queries with given id

我有一个 table,其中包含来自不同设备的数据。每个设备都有一个ID。每次设备状态改变时都会执行一条insert语句。

我想select所有设备的最后条目。

我正在使用此代码:

SELECT device_id, entry_id, data, entry_date
            FROM some_table
            group by device_id
            order by device_id asc, entry_date desc;

但它 returns 我是每个设备的第一个条目,而不是最后一个。

你能帮帮我吗?

试试这个

SELECT t1.device_id, t1.entry_id, t1.data, t1.entry_date
            FROM some_table as t1 inner join
(
select device_id,max(entry_date) as entry_date from some_table
group by device_id
) as t2 on t1.device_id=t2.device_id and t1.entry_date=t2.entry_date 

排序取决于每个字段的顺序。所以如果你想按日期先排序,改变排序顺序:

SELECT device_id, entry_id, data, entry_date
            FROM some_table
            group by device_id
            order by  entry_date desc,device_id asc