SQL 如何获取时间最新的记录

-- 方法1
select a.* 
 from table1 a
 where not exists(select 1 
                  from table1 b
                  where b.name=a.name and b.time>a.time);
 
-- 方法2
select a.*
 from table1 a
 inner join
 (select name,
         max(time) as maxtime
  from table1 
  group by name) b on a.name=b.name and a.time=b.maxtime;

简要说明:

select 1 from table ---查询符合条件的记录的行数。

max(time) as maxtime ---起“别名”。

适用场景:

例子:table1 :
userId       name            time
107         tom           2017/6/21 22:34 
107         tom           2017/6/24 10:21 
208       jack          2017/6/21 22:36 
208       jack          2017/11/15 10:46 
208       jack          2017/1/19 9:12 
208       jack          2017/1/10 13:57 
208       jack          2017/1/22 10:08 
309       ben           2017/6/22 12:54 
309       ben           2017/3/11 9:16 

猜你喜欢

转载自blog.csdn.net/Scarlett1994/article/details/84976457