【发布时间】:2023-03-11 06:59:01
【问题描述】:
我需要在一个表中插入多行,通过一次选择从另一个表中获取 ID。
例如,如果我有以下情况:
create table book (
id uuid primary key default gen_random_uuid(),
title varchar not null
);
create table chapter (
id uuid primary key gen_random_uuid(),
title varchar not null,
book_id uuid references book(id) not null
);
insert into book ("title")
select "foo bar";
我想为一本书插入一些章节,每个章节都有自己的行,我知道其标题但不知道 ID,如何在单个查询中执行此操作?
我尝试过类似的方法,但它不起作用:
insert into chapter ("title", "book_id")
select
values ("Chapter One", "Second Chapter")
book.id
from book
where book.title = "foo bar";
生成的章节表类似于:
chapter
-----
id, title, book_id
8e7fb95b-7bde-45fb-bd81-fba4e29652c0, "Chapter One", eef8e56c-95d4-452b-bd64-ceccae435495
afdd22d3-bfc0-4382-b275-20f89ca0bc03, "Second Chapter", eef8e56c-95d4-452b-bd64-ceccae435495
【问题讨论】:
-
每一章都应该是自己的行
标签: sql postgresql