MySQL刪除重複記錄並保留記錄id最大的一條

一、查詢重複的數據,
    先按學號分組,分組後若是隻有一條就不是重複,因此group 分組後必須用 having 過濾分組後的結果,對分組中條數大於1條才選中。mysql

select * from student where sno in (select sno from student group by sno having count(sno) > 1) 
select sno from (select * from student where sno in (select sno from student group by sno having count(sno) > 1)) t sql

二、查詢每一個分組中id最大的記錄id。spa

select max(id) id from student group by sno having count(*) > 1
select id from (select max(id) id from student group by sno having count(*) > 1) s3d

三、接下來就是刪除,原理是什麼?刪除掉第一個查詢裏面的重複記錄,可是這個記錄又不能在第二次查詢出來最大id的結果裏面。blog

delete from student where id in (select id from (select * from student where sno in (select sno from student group by sno having count(sno) > 1)  order by sname) t) and id not in (select id from (select max(id) id from student group by sno having count(*) > 1) s)ci

上面的綠色是要嵌套一層select,爲何要嵌套select ???
不取別名會出現:You can't specify target table 'XXX' for update in FROM clause
緣由:由於 更新數據時使用了查詢,而查詢的數據又作更新的條件,mysql不支持這種方式。
解決方案:這句話中必定要取別名。
get

相關文章
相關標籤/搜索