欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MySQL去重保留最大的那条记录(取最新的记录)

程序员文章站 2022-09-27 23:55:20
以用户登录日志表为例,取用户最近登录的设备 1 SET NAMES utf8mb4; 2 SET FOREIGN_KEY_CHECKS = 0; 3 4 -- 5 -- Table structure for t_login_log 6 -- 7 DROP TABLE IF EXISTS `t_lo ......

以用户登录日志表为例,取用户最近登录的设备

 1 set names utf8mb4;
 2 set foreign_key_checks = 0;
 3 
 4 -- ----------------------------
 5 -- table structure for t_login_log
 6 -- ----------------------------
 7 drop table if exists `t_login_log`;
 8 create table `t_login_log` (
 9   `id` int(11) not null auto_increment,
10   `user_id` int(11) not null comment '用户id',
11   `device_name` varchar(32) collate utf8mb4_bin not null comment '登录设备',
12   `login_time` datetime not null default current_timestamp on update current_timestamp comment '登录时间',
13   primary key (`id`)
14 ) engine=innodb auto_increment=9 default charset=utf8mb4 collate=utf8mb4_bin;
15 
16 -- ----------------------------
17 -- records of t_login_log
18 -- ----------------------------
19 begin;
20 insert into `t_login_log` values (1, 1121, 'iphone 6s', '2019-07-01 19:20:25');
21 insert into `t_login_log` values (2, 2120, 'vivo x20', '2019-06-28 16:21:11');
22 insert into `t_login_log` values (3, 1607, 'huawei p30', '2019-07-04 19:21:59');
23 insert into `t_login_log` values (4, 2120, 'vivo x20', '2019-06-30 19:22:34');
24 insert into `t_login_log` values (5, 2120, 'vivo x20', '2019-07-04 19:23:07');
25 insert into `t_login_log` values (6, 1121, 'ipad mini', '2019-07-03 19:23:25');
26 insert into `t_login_log` values (7, 1607, 'iphone 8 plus', '2019-06-30 19:24:06');
27 insert into `t_login_log` values (8, 1970, 'mi8', '2019-07-03 19:25:00');
28 commit;
29 
30 set foreign_key_checks = 1; 

自连接,取最新的记录

1 select * from t_login_log order by user_id;
2 
3 select 
4 	t1.* 
5 from t_login_log t1
6 	left join t_login_log t2 on t1.user_id = t2.user_id and t1.login_time < t2.login_time 
7 where t2.id is null; 

效果

MySQL去重保留最大的那条记录(取最新的记录)

 

MySQL去重保留最大的那条记录(取最新的记录)