该表是一张大表,数百万条记录。
表1有三栏
ID,列X和列Y.目前我正在使用" in"声明很慢;特别是在大表中。我希望在不使用in语句的情况下提高此更新语句的性能。非常感谢任何帮助
Update [Table1] set Column_X='Delete' where Column_Y in(
select distinct (Column_Y) from [Table1] where Column_X='Delete'
)
result before running script
Table 1
ID Column X Column Y
1 Delete CAT
2 x1 CAT
3 x1 CAT
4 x1 COW
5 x1 COW
6 x2 Moon
7 Delete Chicken
Intended result after running script
Table 1
ID Column X Column Y
1 Delete CAT
2 Delete CAT
3 Delete CAT
4 x1 COW
5 x1 COW
6 x2 Moon
7 Delete Chicken
答案 0 :(得分:1)
您可以在此使用exists子句。
Update [Table1] set Column_X='Delete' from [Table1] t1where exists(
select t2.Column_Y
from [Table1] t2
where t2.Column_X = 'Delete'
and t2.Column_Y = t1.Column_Y)
它应该比“in”子句快一点。
P.S。:从不使用“in”,因为它进行全表扫描。 “存在”条款应该适用于几乎所有情况。
答案 1 :(得分:1)
您可以在FROM子句中多次使用同一个表,例如:
update Table1
set Column_X = 'Delete'
from Table1 a, Table1 b
where a.Column_Y = b.Column_Y
and b.Column_X = 'Delete'
更新会影响Table1的第一个实例,即" a"。