删除其他表中不存在记录的位置

时间:2013-07-10 13:14:28

标签: sql sql-server performance sql-delete

我有2个表:Table1(ID,Table2ID,Col1,....)和Table2(ID,Col1,....)。 Table2ID是Table2的外键引用。我想编写一个查询来删除Table2中的记录,其中Table1中不存在ID(Table2ID)。表1中的记录计数> 3亿和表1> 1亿。我有两个问题,但我不确定哪一个会更快:

查询1(无效):

delete from Table2
select ID from Table2
except
select Table2ID from Table1

查询2:

delete from Table2
where ID not in (select distinct Table2ID from Table1)

3 个答案:

答案 0 :(得分:1)

试试这个......

select * 
into #temptable2
from table2 t2,table1 t1 
where t1.table2id = t2.id;

truncate table table2;

insert into table2
select * from #temptable2;    

答案 1 :(得分:0)

Query2更快

delete from Table2
where ID not in (select distinct Table2ID from Table1)

答案 2 :(得分:0)

这会更快:

DELETE B
FROM table1 a
LEFT OUTER JOIN table2 b ON a.table2id = b.id 
WHERE b.id IS null