假如有這樣一張表news:欄位:id,title,time,image,author,現在表中有1萬多條記錄,其中title重覆的有上千條。如何才能一次性將title重覆記錄刪除呢? ...
假如有這樣一張表news:欄位:id,title,time,image,author,現在表中有1萬多條記錄,其中title重覆的有上千條。如何才能一次性將title重覆記錄刪除呢?
ID | Title | Time | image | author |
1 | 我是高富帥 | 1234 | pic1.jpg | 1 |
2 | 我是白富美 | 1233 | pic2.jpg | 2 |
3 | 我是高富帥 | 1235 | pic3.jpg | 3 |
本人使用sqlserver資料庫。
現在先將所有的重覆數據顯示出來:
SELECT id,title,time,image,author FROM news WHERE (title IN (SELECT title FROM news GROUP BY title HAVING (COUNT(title) > 1)))
刪除多餘的記錄
delete from news WHERE (title IN (SELECT title FROM news GROUP BY title HAVING (COUNT(title) > 1))) AND (id NOT IN (SELECT MIN(id) AS nid FROM news GROUP BY title HAVING (COUNT(title) > 1)))
使用min的原因是保留髮布時間最早的記錄,如果要保留時間最後發佈的可以使用max