0

我有 2 个表:Table1 (ID, Table2ID, Col1,....) 和 Table2 (ID, Col1,....)。Table2ID 是来自 Table2 的外键引用。我想编写一个查询以从 Table2 中删除 ID(Table2ID)在 Table1 中不存在的记录。表 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)
4

3 回答 3

1

尝试这个...

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

truncate table table2;

insert into table2
select * from #temptable2;    
于 2013-07-10T14:14:20.350 回答
0

Query2 更快

delete from Table2
where ID not in (select distinct Table2ID from Table1)
于 2013-07-10T13:15:50.403 回答
0

这会更快:

DELETE B
FROM table1 a
LEFT OUTER JOIN table2 b ON a.table2id = b.id 
WHERE b.id IS null
于 2013-07-10T13:18:53.827 回答