首页 > 解决方案 > 从具有匹配值对的另一个表中插入

问题描述

     Table_One                                            Table_Two

ID ----- | ----- P_Name                              ID ----- | ----- P_Name
1X2      |  Name1                                             | Name1
1X3      |  Name2                                             | Name2

我想将 ID 插入 Table_Two 中 ID 与 Table_One 匹配的位置。例如 Table_2 上 Name2 的 ID 需要是 1X3

这是我到目前为止所拥有的,我遇到了错误。我对 SQL 很陌生。要温柔。

哦,我也在使用 PostgreSQL。

insert into table_two (ID)
select "ID" from Table_One
where Table_One.P_Name = Table_Two.P_name

标签: sqlpostgresql

解决方案


您想更新表,而不是insertUpdate更改中的值。 Insert添加新行。所以:

update table_two t2
    set id = t1.id
    from table_one t1
    where t1.name = t2.name;

推荐阅读