简体   繁体   English

postgreSQL根据ID匹配从一个表更新到另一个表

[英]postgreSQL update from one Table to another based on a ID match

I have a database with sites and counties . 我有一个包含sitescounties的数据库。 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.namesites.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.

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