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

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

 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去重保留最大的那条记录(取最新的记录)_第1张图片

 

MySQL去重保留最大的那条记录(取最新的记录)_第2张图片 

 

你可能感兴趣的:(MySQL去重保留最大的那条记录(取最新的记录))