buguge - Keep it simple,stupid

知识就是力量,但更重要的,是运用知识的能力why buguge?

导航

【SQL干货】删除重复数据记录

如何删除数据表里的重复数据记录?还在用in或not in 吗?

来吧,教你一招!

(本文SQL可以直接拿去执行)

 

DROP TABLE tmpUser,tmp2;

CREATE TEMPORARY TABLE tmpUser
SELECT 1 AS id,'谷爱凌' AS usr UNION
SELECT 2, '谷爱凌' UNION
SELECT 3, '麦克戴维德' UNION
SELECT 4, '羽生结弦' UNION
SELECT 5,'谷爱凌' UNION
SELECT 6, '麦克戴维德';

-- 【注意:mysql中,select *里无法另行指定多余字段,例如:select 'dd', *是不行的。这时,只能显示指定字段】
SELECT '【原始数据】', id, usr FROM tmpUser ORDER BY 3, 2;

 

 

-- mysql不支持with..as ,这里用临时表
CREATE TEMPORARY TABLE tmp2 SELECT usr, MIN(id) AS minId FROM tmpUser GROUP BY usr HAVING COUNT(1)>1;
SELECT *FROM tmp2;

 

 

-- 如下语句,通过关联上面的临时表,实现删除重复数据
DELETE m
FROM tmpUser m
JOIN tmp2 b ON m.usr=b.usr AND m.id>b.minId;
SELECT '【删除重复记录后的结果数据】', id, usr FROM tmpUser;

 

posted on 2022-02-26 21:28  buguge  阅读(127)  评论(0编辑  收藏  举报