相关疑难解决方法(0)

如何插入包含外键的行?

使用 PostgreSQL v9.1。我有以下表格:

CREATE TABLE foo
(
    id BIGSERIAL     NOT NULL UNIQUE PRIMARY KEY,
    type VARCHAR(60) NOT NULL UNIQUE
);

CREATE TABLE bar
(
    id BIGSERIAL NOT NULL UNIQUE PRIMARY KEY,
    description VARCHAR(40) NOT NULL UNIQUE,
    foo_id BIGINT NOT NULL REFERENCES foo ON DELETE RESTRICT
);
Run Code Online (Sandbox Code Playgroud)

假设第一个表foo是这样填充的:

INSERT INTO foo (type) VALUES
    ( 'red' ),
    ( 'green' ),
    ( 'blue' );
Run Code Online (Sandbox Code Playgroud)

有没有办法bar通过引用foo表轻松插入行?或者我必须分两步完成,首先查找foo我想要的类型,然后在其中插入一个新行bar

这是一个伪代码示例,显示了我希望可以完成的工作:

INSERT INTO bar (description, foo_id) VALUES
    ( …
Run Code Online (Sandbox Code Playgroud)

postgresql foreign-key insert postgresql-9.1

77
推荐指数
3
解决办法
37万
查看次数

标签 统计

foreign-key ×1

insert ×1

postgresql ×1

postgresql-9.1 ×1