MySQL去重保留最大的那条记录(取最新的记录)
数据表:
SQL Code复制内容到剪贴板
- -- ----------------------------
- -- Table structure for 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(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '登录设备',
- `login_time` datetime DEFAULT NULL COMMENT '登录时间',
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
- -- ----------------------------
- -- Records of t_login_log
- -- ----------------------------
- 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');
以用户登录日志表为例,取用户最近登录的设备,自连接,取最新的记录
SQL Code复制内容到剪贴板
- 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;
应该获取的记录是以下红框内的数据
第二种:
SQL Code复制内容到剪贴板
- SELECT t.* FROM (SELECT id,user_id,max(login_time) AS login_time FROM t_login_log GROUP BY user_id) a
- LEFT JOIN t_login_log t
- ON t.user_id=a.user_id AND t.login_time=a.login_time
第三种,不需要关联到ID的情况下,只取最大login_time
SQL Code复制内容到剪贴板
- select user_id, max(login_time) from t_login_log group by user_id;
上一篇 ping指定IP的指定端口
下一篇 PHP保留两位小数的几种方法