Update referencing another table

前提是你 提交于 2019-12-11 06:55:04

问题


I have a statement that needs writing (with generic names for stuff, since this is for work) to update a column 'updCol' in table 'tUpd'. tUpd also has a column 'linkCol' which is present in another table tOther. tOther has another column 'idCol'.

My problem is to update the updCol value of rows in tUpd which correspond via linkCol to rows with a given idCol value.

One solution I think should work is the following;

update
    tUpd
set
    updCol = XXX
where exists (
    select
        idCol
    from
        tOther
    where
        tOther.linkCol = tUpd.linkCol
    and tOther.idCol = MY_ID
)

However, I have worries that this approach will lead to poor performance, since I've been warned of sub-queries in relation to performance before - this sub-query will be run once for each row of tUpd, is this correct?

Has anyone got a better suggestion?

Important Update: my workplace avoids using SQL JOINs at all costs, preferring to join within the where clauses using, eg, where a.col = b.col. This is arguably rather awkward but allows a flexibility in especially logging which I don't fully understand. SO, I'm looking for non-JOIN-using solutions :)


回答1:


Its simply like this

UPDATE DestinationTable
SET DestinationTable.UpdateColumn =  SourceTable.UpdateColumn 
FROM SourceTable
WHERE DestinationTable.JoinColumn = SourceTable.JoinColumn



回答2:


All the above solutions gives an error in Informix as it cannot find the one of the table. Here is a solution for this which worked for me:

update table1
set table1.field2 = (select table2.field2 from table2 where table1.field1 = table2.field1)
where table1.field1 in (select table2.field1 from table2)

edit: A multi-column solution from another question

update table1
set (table1.field2, table2.field3) = (
  (select table2.field2, table2.field3 
     from table2 
     where table1.field1 = table2.field1)
)
where table1.field1 in (select table2.field1 from table2)



回答3:


Maybe it will help you

update tUpd
set tU.updCol = XXX
from tOther tot, tUpd tU   
where tot.linkCol = tU.linkCol
  and tot.idCol = MY_ID

Here is link to similar problem.




回答4:


This works for Informix Databases:

UPDATE dest_table V 
SET field_1 = 
   (SELECT field_1 FROM source_tbl WHERE field_2 IS NULL
   AND field_1 = V.field_1);

Reference



来源:https://stackoverflow.com/questions/12493575/update-referencing-another-table

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