【发布时间】:2019-11-12 18:27:25
【问题描述】:
我有两个表(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 中实现这一点?谢谢。
【问题讨论】:
-
我看到的唯一问题是您试图在一个语句中插入值。所以这不会插入任何东西。如果您尝试将值一一插入
b,2和3将通过,4将被拒绝。
标签: postgresql insert foreign-keys