为什么更新查询需要花费太多时间?
表1
Id table2Id(Unique key)
101 201
102 205
表2
Id table1Id Name bool
201 101 'A' 0
202 101 'B' 0
203 101 'C' 0
205 102 'A' 0
206 102 'B' 0
表1将只包含一个table2 Id(一对一)。但是table2包含多个table1 id(一个(table2)到多个(table1))
update table 2 set bool=1
where Id( select t2.Id from table2 join table1 on t2.Id(PKey)=t1.table2Id(PKey) and t2.Name='A')
此查询需要大约6分钟的时间来更新。如果我在2秒内运行内部选择查询得到结果。
如果我在 t1.Id = t2.table1Id 等条件下更改连接,则会在5秒内执行更新查询。
知道为什么吗?
答案 0 :(得分:0)
这是您的查询,适合您。但是,就任何其他DBMS产品而言,这不是有效的SQL
更新查询。
update table 2 set
where Id( select t2.Id from table2 join table1 on t2.Id(PKey)=t1.table2Id(PKey))
所以,让我用上面的
SQL更新队列来纠正你UPDATE t1 SET table2Id = t2.Id -- Whaterver going to update
FROM table1 t1
INNER JOIN table2 t2
ON t2.Id = t1.Id -- whatever input parameter you have for logical/physical join operation
现在,就性能而言,如果table1(Id)具有主键约束或索引,则上述表现良好。