在PostgreSQL中仅插入现有外键

我有两个表(A和B),并且在B中有一个外键,引用了A。我试图在B中插入行,但是经过了验证,只需在A中插入具有现有键的行即可。

使用此表结构,我要实现以下目标:

create table a (id int primary key);
create table b (a_id int not null);
alter table b add foreign key (a_id) references a(id);

insert into a values (1),(2),(3);
insert into b values (2),(3),(4); -- This should just insert 2,3 and exclude 4,since it doesn't exist in table A.

select * from b; -- The query should return just the foreign key 2 and 3.

类似的东西。有什么方法可以在PostgreSQL中实现呢?谢谢。

dhtz_123 回答:在PostgreSQL中仅插入现有外键

我要做的是从表“ a”中选择ID,并将其插入表“ b”的外键列中。

INSERT INTO b(a_id) SELECT id FROM a;
本文链接:https://www.f2er.com/3115120.html

大家都在问