Using subquery in an update always requires subquery in a where clause?

半世苍凉 提交于 2019-12-23 15:16:08

问题


This is a common SQL query for me:

update table1 set col1 = (select col1 from table2 where table1.ID = table2.ID)
where exists (select 1 from table2 where table1.ID = table2.ID)

Is there any way to avoid having two nearly identical subqueries? This query is an obvious simplification but performance suffers and query is needlessly messy to read.


回答1:


Unfortunately Informix don't support the FROM clause at UPDATE statement. The way to workaround and you will get better results (performance) is change the UPDATE to MERGE statement.

This will work only if your database is version 11.50 or above

MERGE INTO table1 as t1
USING table2 as t2
   ON t1.ID = t2.ID
WHEN MATCHED THEN UPDATE set (t1.col1, t1.col2) = (t2.col1, t2.col2);

Check IBM Informix manual for more information




回答2:


Update with inner join can be used to avoid subqueries

something like this:

update t1 
set col1 = t2.col1
from table1 t1
inner join table2 t2
on t1.ID = t2.ID



回答3:


try this:

 update table1 set col1 = (select col1 as newcol from table2 where table1.ID = table2.ID)
where exists (newcol)


来源:https://stackoverflow.com/questions/19004605/using-subquery-in-an-update-always-requires-subquery-in-a-where-clause

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!