文章出處
文章列表
數據表 sniper_tb 中存在主鍵 id,字段url,現需要在url字段上添加 unique,但由于url存在重復記錄,導致添加失敗。
如何刪除表中多余的url重復記錄,僅保持一條?
思路一
- 將 sniper_tb 表按url字段分組,將其中 count(url) > 1 的記錄存入一個臨時表 tmp中,此臨時表同時包含id字段
- 將 sniper_tb 表中 url 與 tmp.url 相同的記錄找出來設置為集合 tmp2
- tmp2.id 不在臨時表 tmp.id 中的記錄,則為最終需要刪除的記錄
以上思路的select sql語句如下:
select id from sniper_tb where url in (select tmp.url from ( select url,id from sniper_tb where 1=1 group by url having count(url) > 1) tmp) and id not in (select tmp.id from ( select url,id from sniper_tb where 1=1 group by url having count(url) > 1) tmp)
將其中的 sniper_tb、id、url 替換成你本地對應的數據表及字段即可,將最開始的 select id 替換成 delete 即可刪除這些多余的重復記錄。
以上語句中的 where 1=1 是特意占位出來方便替換查詢限制條件的:)
思路二
- 將 sniper_tb 表中的記錄兩兩比較,找出 a.url = b.url 的重復記錄
- 將這些重復記錄中的最小 id 存為一個臨時集合 tmp
- 將 sniper_tb 表中id > tmp.id 的重復記錄刪除
對應的 select sql 語句如下:
select * from sniper_tb a where id > (select min(id) from sniper_tb b where a.url=b.url)
但在mysql中,直接將 select 替換成 delete語句會出現如下報錯:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'a where id > (select min(id) from sniper_tb b where a.url=b.url)' at line 1
mysql的delete寫法有挺多限制,比較好的辦法就是先 create 一個臨時表,用完之后再drop掉,以上語句的 delete 實現為:
create table tmp as select id from sniper_tb a where id > (select min(id) from sniper_tb b where a.url=b.url); delete from sniper_tb where id in(select id from tmp); drop table tmp;
參考資料
文章列表
全站熱搜