MySQL查询重复数据
短信预约 信息系统项目管理师 报名、考试、查分时间动态提醒
假设有一个用户表 user,数据如下:
1、查询表中 uid 重复的数据
SELECT
id,
uid,
name
FROM USER
WHERE uid IN (SELECT
uid
FROM USER
GROUP BY uid
HAVING COUNT(uid) > 1);
2、查询表中重复数据,排除最小id
SELECT
id,
uid,
name
FROM user
WHERE uid IN (SELECT
uid
FROM user
GROUP BY uid
HAVING COUNT(uid) > 1)
AND id NOT IN (SELECT
MIN(id)
FROM user
GROUP BY uid
HAVING COUNT(uid) > 1);
3、删除表中重复数据,如果是重复数据,则保留id最小的一条
DELETE
FROM USER
WHERE id IN (SELECT
u.id
FROM (SELECT
id
FROM USER
WHERE uid IN (SELECT
uid
FROM USER
GROUP BY uid
HAVING COUNT(uid) > 1)
AND id NOT IN (SELECT
MIN(id)
FROM USER
GROUP BY uid
HAVING COUNT(uid) > 1)) AS u);
4、遇到的问题:
一开始直接使用以下语句删除,报错:You can’t specify target table ‘user’ for update in FROM clause
DELETE
FROM USER
WHERE id IN (SELECT
id
FROM USER
WHERE uid IN (SELECT
uid
FROM USER
GROUP BY uid
HAVING COUNT(uid) > 1)
AND id NOT IN (SELECT
MIN(id)
FROM USER
GROUP BY uid
HAVING COUNT(uid) > 1));
查资料后得知:
因为在 MYSQL 里,不能先 select 一个表的记录,在按此条件进行更新和删除同一个表的记录。
解决办法:
将 select 得到的结果,再通过中间表 select 一遍。
SQL如下:
DELETE
FROM USER
WHERE id IN (SELECT
u.id
FROM (SELECT
id
FROM USER
WHERE uid IN (SELECT
uid
FROM USER
GROUP BY uid
HAVING COUNT(uid) > 1)
AND id NOT IN (SELECT
MIN(id)
FROM USER
GROUP BY uid
HAVING COUNT(uid) > 1)) AS u);
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341