學生表student 如下:
id name subject fraction
1 張三 數學 69
2 李四 數學 89
3 張三 數學 69
首先,想要把重複的資料查找出來,我們要了解sql的min()函數,
select min(id) id from student group by
name
,subject,fraction
使用這條sql語句,我們可以得到包含了資訊相同的但id卻為 1 的資訊的表,再搭配使用not in就可以删除id為 3 的重複資訊了。
delete from student where id not in (select id from (select min(id) id from student group by
name
,subject ,fraction)as b)
執行這條sql語句,子查詢隻能得到id為 1 和 2 的資訊,是以delete會删除id為 3 的資訊。
這裡我用了兩條select語句,是因為mysql不允許在子查詢的同時删除原表資料,是以這裡把子查詢的結果建立臨時表存儲,再select其中的id,這樣就可以了。
本人菜鳥,在學習過程中遇到的一個問題,歡迎各位大佬指點。