2017-04-26 62 views
-1

我需要在我的數據庫上運行這個查詢,但它需要永遠。我在桌上有超過1 000 000條記錄。有沒有辦法讓它更有效率?SQL Server:如何使此刪除查詢更有效?

delete 
from CON 
where id in (select id 
      from CON co 
      where not exists (select id 
           from AC ac 
           where ac.ID = co.ID_) 
      ) 
+0

哪個更多,刪除的數量還是剩餘的數量? –

+0

清除次數更多。 – stianzz

+0

你有任何引用CON的外鍵約束嗎? –

回答

0

您可以使用下面的查詢來刪除CON項目不與項目匹配AC

delete co from 
CON co left join 
Ac ac on ac.ID = co.ID_ 
where ac.ID is null 
0

你可以跳過in(),只是使用not exists()

delete 
from con 
where not exists (
    select 1 
    from ac 
    where ac.id = con.id 
    ); 

除非在簡化示例查詢時刪除了其他內容。

0

您想保持較小的交易。嘗試一次刪除10000行,如下所示:

delete TOP (10000)from CON 
where id in (
    select id 
    from CON co 
    where not exists (
    select id 
    from AC ac 
    where ac.ID = co.ID_ 
    ) 
) 
WHILE @@ROWCOUNT > 0 
    delete TOP (10000) from CON 
where id in (
    select id 
    from CON co 
    where not exists (
    select id 
    from AC ac 
    where ac.ID = co.ID_ 
    ) 
) 

您可以嘗試一次試驗1000行或10000行。