[英]How can I update only changed values from another table in PostgreSQL 9.4?
I have this query but updates the whole region_tmp table, which I dont want to, I only need to update a row in region table if anything has changed.我有这个查询但更新了整个 region_tmp 表,我不想这样做,如果有任何更改,我只需要更新区域表中的一行。 I know I can specify which row with the regionid but am looking for something more general since I have a lot of records.
我知道我可以用 regionid 指定哪一行,但我正在寻找更通用的东西,因为我有很多记录。
UPDATE REGION_TMP t SET
REGIONID=R.REGIONID,
REGIONDESCRIPTION=R.REGIONDESCRIPTION
FROM REGION R
WHERE R.REGIONID = T.REGIONID;
REGION TABLE:区域表:
REGIONID![]() |
REGIONDESCRIPTION![]() |
---|---|
1 ![]() |
AMERICA![]() |
2 ![]() |
EUROPE![]() |
3 ![]() |
ASIA![]() |
REGION_TMP TABLE: REGION_TMP 表:
REGIONID![]() |
REGIONDESCRIPTION![]() |
---|---|
1 ![]() |
AMERICA![]() |
2 ![]() |
EUROPE![]() |
3 ![]() |
AFRICA![]() |
My desire output in REGION_TMP:我希望 REGION_TMP 中的 output:
REGIONID![]() |
REGIONDESCRIPTION![]() |
---|---|
1 ![]() |
AMERICA![]() |
2 ![]() |
EUROPE![]() |
3 ![]() |
ASIA![]() |
My guess is that you need to create a duplicate of your REGION table, but you already have a REGION_TMP table, so you just want to update the values that do not match.我的猜测是您需要创建REGION表的副本,但您已经有一个REGION_TMP表,所以您只想更新不匹配的值。
In order to achieve that, you need to join the two tables inside the UPDATE
statement and replace the values of REGION_TMP.REGIONDESCRIPTION
with the corresponding REGION.REGIONDESCRIPTION
where the REGION_ID
applies for both and the REGIONDESCRIPTION
is different:为了实现这一点,您需要在
UPDATE
语句中连接两个表, REGION_TMP.REGIONDESCRIPTION
的值替换为相应的REGION.REGIONDESCRIPTION
,其中REGION_ID
适用于两者,而REGIONDESCRIPTION
不同:
UPDATE REGION_TMP
SET REGIONDESCRIPTION = REGION.REGIONDESCRIPTION
FROM REGION
WHERE REGION_TMP.REGIONID = REGION.REGIONID
AND REGION_TMP.REGIONDESCRIPTION <> REGION.REGIONDESCRIPTION;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.