[英]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. 我在Spring中使用
RunSqlTasklet
来运行此SQL,但实际上将使用postgres,而我的版本无法处理合并,因此请没有合并答案。
Example: 例:
After the update, I want table 1 to look like below 更新后,我希望表1如下所示
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? 如何在不将TABLE1中的列设置为上述特定的,单独的select语句的情况下更新上述查询以使用TABLE2中的值更新TABLE1?
I have Googled and the above is the only thing that seemed to work, but I don't think so. 我已经用Google搜索过了,上面的内容似乎是唯一可行的方法,但是我不这么认为。
You can use the update-join syntax. 您可以使用update-join语法。 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): 基本上,您只需要添加一个带有table2的
from
子句,以及一个带有连接条件(当然,以及您可能想要的任何其他条件)的where
子句:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.