mysql 删除重复数据

时间:2022-05-19 06:23:57

1在日常使用mysql中 前端页面点击次数过多 mysql就会容易产生冗余数据,那这些数据该怎么删除呢

说下思路

查询重复字段id 查询重复字段最小id 删除重复字段ID 保留最小ID

查询重复记录这没的说

SELECT 重复记录字段 from 表 GROUP BY 重复记录字段 HAVING COUNT(*)>1

查询重复字段ID

例如

SELECT id FROM way_bills WHERE source_goods_id in (SELECT source_goods_id from way_bills GROUP BY source_goods_id HAVING COUNT(*)>1)

查询最小ID

SELECT MIN(id) from way_bills GROUP BY source_goods_id HAVING COUNT(*)>1

组合起来完整语句

DELETE
FROM
way_bills
WHERE
id IN (
SELECT
t.id
FROM
( SELECT id FROM way_bills WHERE source_goods_id IN ( SELECT source_goods_id FROM way_bills GROUP BY source_goods_id HAVING COUNT( * ) > 1 ) ) t
)
AND id NOT IN (
SELECT
q.id
FROM
( SELECT MIN( id ) id FROM way_bills GROUP BY source_goods_id HAVING COUNT( * ) > 1 ) q
)

ps

一定要给表起别名 否则你会给他不期而遇

You can't specify target table '表名' for update in FROM clause

就是说你不能查询表的同时删除表 ,你可以给他定义别名相当于定义张虚表,然后查询。嗯,这是我个人理解。