简体   繁体   中英

How do I update TABLE1 with values from TABLE2 without setting columns from TABLE1 to specific, individual select statements?

I want to update one table with a values from another table if those values exist. I am using a RunSqlTasklet in Spring to run this SQL, but will be actually using postgres and my version can't handle merges, so no merge answers please.

Example:

表格1

TABLE2

After the update, I want table 1 to look like below TABLE1_updated

The below works but doing the individual, specific column select part over and over, seems like it could be improved.

UPDATE schema.TABLE1 t1
SET  COLUMN1 = (SELECT t2.COLUMN1 FROM schema.TABLE2 t2 WHERE t1.COLUMN4 = t2.COLUMN4 AND t1.COLUMN5 = t2.COLUMN5)
    ,COLUMN2 = (SELECT t2.COLUMN2  FROM schema.TABLE2 t2 WHERE t1.COLUMN4 = t2.COLUMN4 AND t1.COLUMN5 = t2.COLUMN5)
    ,COLUMN3 = (SELECT t2.COLUMN3 FROM schema.TABLE2 t2 WHERE  t1.COLUMN4 = t2.COLUMN4 AND t1.COLUMN5 = t2.COLUMN5)
WHERE EXISTS (
              SELECT 1 FROM schema.TABLE2 t2 
              WHERE t1.COLUMN4 = t2.COLUMN4
              AND t1.COLUMN5 = t2.COLUMN5
              );

How do I update the above query to update TABLE1 with values from TABLE2 without setting columns from TABLE1 to specific,individual select statements above?

I have Googled and the above is the only thing that seemed to work, but I don't think so.

You can use the update-join syntax. Basically, you just need to add a from clause with table2, and a where clause with the join condition (and any other condition you may want, of course):

UPDATE schema.TABLE1 t1
SET    t1.COLUMN1 = t2.COLUMN1,
       t1.COLUMN2 = t2.COLUMN2,
       t1.COLUMN3 = t2.COLUMN3
FROM   schema.TABLE2 t2
WHERE  t1.COLUMN4 = t2.COLUMN4 AND t1.COLUMN5 = t2.COLUMN5

you can do this too

--Select *
Update T1 
SET    t1.COLUMN1 = t2.COLUMN1,
       t1.COLUMN2 = t2.COLUMN2,
       t1.COLUMN3 = t2.COLUMN3
 from schema.Table1 T1 Inner JOIN
      schema.Table2 T2
           on T1.Column4 =T2.Column4 and t1.COLUMN5 = t2.COLUMN5 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM