[英]postgreSQL update from one Table to another based on a ID match
I have a database with sites
and counties
. 我有一个包含
sites
和counties
的数据库。 Every site is located in one county. 每个站点都位于一个县。 In the
sites
table, the county is already mentioned but I want to replace it with the ID
, which in is the other table. 在
sites
表中,已经提到了该县,但我想用ID
替换它,而在另一个表中。
My update code is as follows: 我的更新代码如下:
UPDATE sites
SET cgid = c.gid
FROM (select c.gid as a from counties c
INNER JOIN sites s
ON c.name = s.county) p;
The table sites
is updated, although every value in the cgid
column is the same (the ID of the first county). 虽然
cgid
列中的每个值都相同(第一个县的ID),但表sites
已更新。 What can I do to get the right values? 我能做些什么来获得正确的价值观?
The target table of an update
statement should never be repeated in the from
clause 不应在
from
子句中重复update
语句的目标表
So I think you want this: 所以我想你想要这个:
UPDATE sites s
SET cgid = c.gid
FROM counties c
where c.name = s.county;
This assumes that counties.name
and sites.county
are both unique. 这假设
counties.name
和sites.county
都是唯一的。
UPDATE sites AS s
SET cgid = c.gid
FROM counties AS c
WHERE c.name = s.county
You don't need a JOIN
. 你不需要
JOIN
。 Instead, you just need to connect the two tables in the WHERE
clause: 相反,您只需要连接
WHERE
子句中的两个表:
UPDATE sites s
SET cgid = c.gid
FROM counties c
WHERE c.name = s.county;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.