刪除重複資料SQL的解析

2021-09-10 03:43:38 字數 1229 閱讀 5980

新人小白,不對請指教謝謝,因為只是弄了個簡單的測試所以名字就沒有過多的要求了,希望各位見諒。

delete

from

awhere

id in (

select

s.id

from

(select

a.id

from

awhere

a.id not in (

select

idfrom

agroup by

c_1,

c_2)

) s);

上面是全部的刪除語句具體資料借鑑了劉宇ly的部落格,我還做了些許資料增加

下面我來解釋下這條sql

首先查詢出重複的資料的id

select

s.id

from

(select

a.id

from

awhere

a.id not in (

select

idfrom

agroup by

c_1,

c_2)

) s

使用了子查詢,這裡將查詢結果設定別名s方便後面操作,group by 後面我覺得應該是判斷資料是否重複的條件

子查詢最裡面的這一句主要是根據判斷條件獲得id,可以看到我和1相同的還有2,3。但經過判斷後只查出來1,所以這裡選擇了 a.id not in 來進行下一步的排除,因為這個也處於子查詢中所以條件我想主要還是裡面的 group by 那麼這裡使用 not in 出錯的可能性也能減少

最外層刪除的判斷採用了 in 主要是擔心返回的資料不止一條

又採用了一層子查詢,可能可以減少掉這一層,還有其他事情就沒去測試了,

最後將這些結果作為 in 中的條件進行刪除。

sql刪除重複資料

1 建立表 create table dbo test id numeric 18,0 identity 1,1 not null primary key,name varchar 200 collate chinese prc ci as null remark varchar 1024 coll...

sql刪除重複資料

sql刪除重複資料 如果該錶需要刪除重複的記錄 重覆記錄保留1條 可以按以下方法刪除 select distinct into tmp from tablename drop table tablename select into tablename from tmp drop table tmp ...

SQL刪除重複資料

這個應用場景也不多說了 with c as select orderid,row number over partition by orderid order by select null as nfrom sales.myorders delete from c where n 1 利用row n...