Mysql5.7--去除每组内时间最小的那一行数据
先贴出来原始数据和处理后的数据对比
处理前

处理后

一 、 先做一些实验数据,下边贴出的代码可以粘贴到查询窗口,直接执行即可
SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for test1 -- ---------------------------- DROP TABLE IF EXISTS `test1`; CREATE TABLE `test1` ( `id` int(0) NOT NULL, `pre_id` int(0) NULL DEFAULT NULL, `trans_time` datetime(0) NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of test1 -- ---------------------------- INSERT INTO `test1` VALUES (1, 1, '2022-08-05 13:42:48'); INSERT INTO `test1` VALUES (2, 1, '2022-08-04 13:43:06'); INSERT INTO `test1` VALUES (3, 1, '2022-08-05 13:43:17'); INSERT INTO `test1` VALUES (4, 2, '2022-08-03 13:43:33'); INSERT INTO `test1` VALUES (5, 2, '2022-08-05 13:43:46'); INSERT INTO `test1` VALUES (6, 2, '2022-08-06 13:43:57');
二、具体实现如下
SELECT a.* FROM `test1` a LEFT JOIN ( SELECT pre_id, min( trans_time ) trans_time FROM `test1` GROUP BY pre_id ) b ON a.pre_id = b.pre_id AND a.trans_time = b.trans_time where b.pre_id is null
三、补充。如果可以确定每一行数据的时间戳是唯一的,那么可以按下面的方式进行实现也可以
SELECT a.* FROM `test1` a where a.trans_time not in (SELECT min( trans_time ) trans_time FROM `test1` GROUP BY pre_id)
四、如果你的Mysql版本是8以上,可以使用开窗排序,去掉时间最小的

浙公网安备 33010602011771号