【问题标题】:Insert only existing foreign keys in PostgreSQL [duplicate]仅在 PostgreSQL 中插入现有的外键 [重复]
【发布时间】: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 中实现这一点?谢谢。

【问题讨论】:

标签: postgresql insert foreign-keys


【解决方案1】:

我要做的是从表“a”中选择 id 并将它们插入到表“b”的外键列中。

INSERT INTO b(a_id) SELECT id FROM a;

【讨论】:

    猜你喜欢
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    • 2010-12-01
    • 2018-04-04
    • 1970-01-01
    • 2022-11-07
    相关资源
    最近更新 更多