mysql过滤表中重复数据,查询表中相同数据的最新一条数据

先查询表几条demo数据,名字相同,时间不同

select id,name,create_date from sys_user 

方法1:最简单,且字段全部相同,排除其他字段不同; 

先对表按照时间desc排序,在查询该层使用group by 语句,它会按照分组将你排过序的数据的第一条取出来

select id,name,create_date from ( select * from sys_user order by create_date  desc) a group by a.name 

方法2:使用not exists,该方法通过相同名字的不同创建的时间进行比较

select id,name,create_date from sys_user a

where not exists (select * from sys_user b where a.name = b.name and a.create_date < create_date )  ;

方法3:使用内关联的方式;

select * from sys_user a
      inner join (
        -- 先查询出最后一条数据的时间
        select id,name, MAX(create_date) create_date from sys_user
 group by name
      ) b on a.name = b.name and a.create_date = b.create_date  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章