SQL 删除重复数据保留最新的一条
SQL 面试 大约 611 字数据表
mysql> select * from test;
+----+--------+---------------------+
| id | name | cdate |
+----+--------+---------------------+
| 1 | abc | 2022-02-08 16:45:13 |
| 2 | xxxxx | 2022-02-08 17:04:32 |
| 3 | xxxxx | 2022-02-08 16:45:13 |
| 4 | zzzsss | 2022-02-08 16:45:13 |
| 5 | aaa | 2022-02-08 16:45:13 |
| 6 | zzz | 2022-02-08 16:45:13 |
+----+--------+---------------------+
MySQL
delete from test where id not in (
select t.id from (
select max(id) as id from test group by name
) t
)
解析
关键在于分组后找到最新的一条数据,可以在group by
后使用聚合函数max()
,将最大的id
取出来,然后删除条件使用not in
。
阅读 335 · 发布于 2022-04-11
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
Spring Boot 2.3.0 不再包含 Validation阅读 1320
-
MySQL 视图阅读 1237
-
Golang 预定义标识符阅读 1440
-
PostgreSQL 获取本月第一天时间戳等信息阅读 2828
-
Linux 之定时任务 crontab 无法启动阅读 3114
-
Java 并发编程之 ConcurrentSkipListMap阅读 489
-
微信小程序基于 Parser 添加长按复制、代码高亮等功能阅读 3080
-
算法:二分查找阅读 501
-
PhpStorm 设置大括号不换行阅读 5032
-
Oracle ORA-01502: index 'INDEX_NAME' or partition of such index is in unusable state阅读 1300