大家好,我是考100分的小小码 ,祝大家学习进步,加薪顺利呀。今天说一说MySQL查询重复数据「终于解决」,希望您对编程的造诣更进一步.
假设有一个用户表 user,数据如下:
1、查询表中 uid 重复的数据
SELECT id, uid, name FROM USER WHERE uid IN (SELECT uid FROM USER GROUP BY uid HAVING COUNT(uid) > 1);
代码100分
2、查询表中重复数据,排除最小id
代码100分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
代码100分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);
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
转载请注明出处: https://daima100.com/8425.html