SQL Server:如何使此删除查询更有效?

时间:2017-04-26 17:38:02

标签: sql sql-server performance

我需要在我的数据库上运行此查询,但这需要永远。我在表中有超过1 000 000条记录。有没有办法让它更有效率?

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

3 个答案:

答案 0 :(得分:0)

您可以使用以下查询删除CON中与AC

中的项目不匹配的项目
delete co from 
CON co left join
Ac ac on ac.ID = co.ID_
where ac.ID is null

答案 1 :(得分:0)

您可以跳过in()并使用not exists()

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

除非在简化示例查询时删除了其他内容。

答案 2 :(得分: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行。