获取数据库中多个重复信息最新一条的方法

1.排序加分组。

select id,name,updateTime from (
    select id,name,updateTime 
    from table_user 
    -- 注意这里排序列要符合实际要筛的业务
    order by id,updateTime desc
) t
group by t.id

使用先排序,在分组的情况,可能因为MySQL子查询机制导致子查询排序结果失效(如:外部查询也有分组,排序,having等),导致最终结果不符合业务结果。可以使用distinct(id),保证子查询排序不失效。

2.使用唯一标识。

select id,name,updateTime 
from table_user where concat_ws('_', id, updateTime ) in ( select concat_ws('_', id, max(updateTime) ) from table_user group by t.id ) t

 3.表中有自增的id,可以先分组取Max(id),然后根据id查。

posted @ 2022-05-26 22:56  对月当歌  阅读(745)  评论(0)    收藏  举报