背景
数据库中,不小心插入了重复的数据,想删除多出来的
测试数据
代码语言: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
);