如何实现 MySQL 删除重复记录并且只保留一条
程序员的成长之路
共 3223字,需浏览 7分钟
·
2020-10-25 10:23
阅读本文大概需要 4 分钟。
一、单个字段的操作
分组介绍
Select 重复字段 From 表 Group By 重复字段 Having Count(*)>1
GROUP BY <列名序列>
HAVING <组条件表达式>
1. 查询全部重复的数据
Select * From 表 Where 重复字段 In (Select 重复字段 From 表 Group By 重复字段 Having Count(*)>1)
2. 删除全部重复试题
DELETE
FROM
dept
WHERE
dname IN (
SELECT
dname
FROM
dept
GROUP BY
dname
HAVING
count(1) > 1
)
[Err] 1093 - You can't specify target table 'dept' for update in FROM clause
3. 查询表中多余重复试题(根据depno来判断,除了rowid最小的一个)
a. 第一种方法
SELECT
*
FROM
dept
WHERE
dname IN (
SELECT
dname
FROM
dept
GROUP BY
dname
HAVING
COUNT(1) > 1
)
AND deptno NOT IN (
SELECT
MIN(deptno)
FROM
dept
GROUP BY
dname
HAVING
COUNT(1) > 1
)
b. 第二种方法
SELECT *
FROM
dept
WHERE
deptno NOT IN (
SELECT
dt.minno
FROM
(
SELECT
MIN(deptno) AS minno
FROM
dept
GROUP BY
dname
) dt
)
c. 补充第三种方法
SELECT
*
FROM
table_name AS ta
WHERE
ta.唯一键 <> ( SELECT max( tb.唯一键 ) FROM table_name AS tb WHERE ta.判断重复的列 = tb.判断重复的列 );
4. 删除表中多余重复试题并且只留1条
a. 第一种方法:
DELETE
FROM
dept
WHERE
dname IN (
SELECT
t.dname
FROM
(
SELECT
dname
FROM
dept
GROUP BY
dname
HAVING
count(1) > 1
) t
)
AND deptno NOT IN (
SELECT
dt.mindeptno
FROM
(
SELECT
min(deptno) AS mindeptno
FROM
dept
GROUP BY
dname
HAVING
count(1) > 1
) dt
)
b. 第二种方法(与上面查询的第二种方法对应,只是将select改为delete)
DELETE
FROM
dept
WHERE
deptno NOT IN (
SELECT
dt.minno
FROM
(
SELECT
MIN(deptno) AS minno
FROM
dept
GROUP BY
dname
) dt
)
c. 补充第三种方法(评论区推荐的一种方法)
DELETE
FROM
table_name AS ta
WHERE
ta.唯一键 <> (
SELECT
t.maxid
FROM
( SELECT max( tb.唯一键 ) AS maxid FROM table_name AS tb WHERE ta.判断重复的列 = tb.判断重复的列 ) t
);
二、多个字段的操作
DELETE
FROM
dept
WHERE
(dname, db_source) IN (
SELECT
t.dname,
t.db_source
FROM
(
SELECT
dname,
db_source
FROM
dept
GROUP BY
dname,
db_source
HAVING
count(1) > 1
) t
)
AND deptno NOT IN (
SELECT
dt.mindeptno
FROM
(
SELECT
min(deptno) AS mindeptno
FROM
dept
GROUP BY
dname,
db_source
HAVING
count(1) > 1
) dt
)
总结
在经常查询的字段上加上索引
将*改为你需要查询出来的字段,不要全部查询出来
小表驱动大表用IN,大表驱动小表用EXISTS。IN适合的情况是外表数据量小的情况,而不是外表数据大的情况,因为IN会遍历外表的全部数据,假设a表100条,b表10000条那么遍历次数就是100*10000次,而exists则是执行100次去判断a表中的数据是否在b表中存在,它只执行了a.length次数。至于哪一个效率高是要看情况的,因为in是在内存中比较的,而exists则是进行数据库查询操作的
别忘记点个在看,咱们下篇见!
慢一点才能更快
推荐阅读:
微信扫描二维码,关注我的公众号
朕已阅
评论