MySQL删除重复数据中ID较大的数据

2024-01-23 15:57:55 浏览数 (2)

背景

数据库中,不小心插入了重复的数据,想删除多出来的

测试数据

代码语言:javascript复制
CREATE TABLE user (
  id INT PRIMARY KEY,
  username VARCHAR(255)
);

INSERT INTO user (id, username) VALUES
(1, 'zhangsan'),
(2, 'lisi'),
(3, 'zhangsan'),
(4, 'lisi'),
(5, 'wangwu'),
(6, 'zhaoliu'),
(7, 'zhaoliu');

筛选指定重复数据中ID较大的数据

代码语言:javascript复制
SELECT max(id), username
FROM user where username in ('zhangsan','lisi')
GROUP BY username;

删除重复的数据

代码语言:javascript复制
DELETE FROM user WHERE id IN (
    SELECT id
        FROM (
            SELECT max(id) as id
            FROM user where username in ('zhangsan','lisi')
            GROUP BY username
    ) as subquery
);

0 人点赞