继续以student表为例
建表和数据看连接
现在的要求是删除掉重复名称的数据只保留id最小的一条
第一钟最容易想到的就是使用not in 出所有不重复的id
DELETE from student WHERE id not in(
SELECT min(id) id from student_copy1 GROUP BY Sname);
这里会报错You can’t specify target table ‘student’ for update in FROM clause
因为MySQL 不能先select一个表的记录,在按此条件进行更新和删除同一个表的记录
所以改成子查询即可
DELETE from student WHERE id not in( SELECT id from (
SELECT min(id) id from student_copy1 GROUP BY Sname)b )
我们之前一直有听说not in 是不会走索引的,但是测试的时候发现not in 的是主键的时候是会走range索引的
第二种使用join 查出所有重复的名字
DELETE a from student a JOIN
(SELECT Sname,min(id)id from student GROUP BY Sname HAVING count(*) >1) b on a.Sname = b.Sname where a.id > b.id;