Sql 使用约束将列从一个表插入到另一个表

Sql 使用约束将列从一个表插入到另一个表,sql,postgresql,Sql,Postgresql,我有两张表:图例和临时表。temp有一个ID和帐户ID,legend有一个ID、帐户ID和其他列。temp中的ID和图例中的ID类似。account_id列为空,我想将相关account_id从temp导入legend。我正在使用PostgreSQL 我正在尝试下面的查询,但它没有像我期望的那样工作。将创建新行,并将帐户id添加到新行中,而不是添加到相应的帐户id中 insert into legend(account_id) select temp.account_id from legend

我有两张表:图例和临时表。temp有一个ID和帐户ID,legend有一个ID、帐户ID和其他列。temp中的ID和图例中的ID类似。account_id列为空,我想将相关account_id从temp导入legend。我正在使用PostgreSQL

我正在尝试下面的查询,但它没有像我期望的那样工作。将创建新行,并将帐户id添加到新行中,而不是添加到相应的帐户id中

insert into legend(account_id)
select temp.account_id
from legend, temp
where legend.advent_id=temp.id;
它将帐户id插入错误的位置,而不是插入相应的帐户id

insert into legend(account_id)
select temp.account_id
from legend, temp
where legend.advent_id=temp.id;
我使用以下查询进行检查:

select advent_id, account_id from legend where account_id is not null;

“我的插入查询”中的具体问题是什么?

如果您试图修改现有行,而不是添加行,那么您需要的是
更新
查询,而不是
插入
查询

可以将联接表用作
更新的目标
;在您的示例中:

UPDATE legend
JOIN temp
SET legend.account_id = temp.account_id
WHERE(temp.id = legend.advent_id);

JOIN
在这里非常关键-我想如果您只想更新一个特定的
advent\u id
,您可以对子查询执行一些操作。它给了我一个错误:更新legend\u backup JOIN temp set legend\u backup.account\u id=temp.account\u id其中temp.id=legend\u backup.advent\u id;错误:字符22第1行的“连接”处或附近出现语法错误:更新图例\u备份连接临时集图例\u备份。帐户\u id=…此查询对我有效:)但不确定是否完美:|更新图例\u备份集帐户\u id=temp.account\u id from temp where(temp.id=图例\u备份.id);我用来检查的查询提供了更好的输出。我是否在正确的轨道上?我将检查查询修改为:从图例备份中选择帐户id,其中帐户id不为空;