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

gHOST

2020-03-06 13:01:44

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

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for t_login_log
-- ----------------------------
DROP TABLE IF EXISTS `t_login_log`;
CREATE TABLE `t_login_log` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL COMMENT '用户ID',
  `device_name` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '登录设备',
  `login_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '登录时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;

-- ----------------------------
-- Records of t_login_log
-- ----------------------------
BEGIN;
INSERT INTO `t_login_log` VALUES (1, 1121, 'iPhone 6s', '2019-07-01 19:20:25');
INSERT INTO `t_login_log` VALUES (2, 2120, 'vivo x20', '2019-06-28 16:21:11');
INSERT INTO `t_login_log` VALUES (3, 1607, 'huawei P30', '2019-07-04 19:21:59');
INSERT INTO `t_login_log` VALUES (4, 2120, 'vivo x20', '2019-06-30 19:22:34');
INSERT INTO `t_login_log` VALUES (5, 2120, 'vivo x20', '2019-07-04 19:23:07');
INSERT INTO `t_login_log` VALUES (6, 1121, 'iPad mini', '2019-07-03 19:23:25');
INSERT INTO `t_login_log` VALUES (7, 1607, 'iPhone 8 Plus', '2019-06-30 19:24:06');
INSERT INTO `t_login_log` VALUES (8, 1970, 'MI8', '2019-07-03 19:25:00');
COMMIT;

SET FOREIGN_KEY_CHECKS = 1; 

自连接,取最新的记录

SELECT * FROM t_login_log ORDER BY user_id;

SELECT 
  t1.* 
FROM t_login_log t1
  LEFT JOIN t_login_log t2 ON t1.user_id = t2.user_id AND t1.login_time < t2.login_time 
WHERE t2.id IS NULL; 

结果

表

结果

转自:https://www.cnblogs.com/cjsblog/p/11134518.html