Pergunta

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.

Foi útil?

Solução

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

Outras dicas

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

try this:

 update table1 set col1 = (select col1 as newcol from table2 where table1.ID = table2.ID)
where exists (newcol)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top