【问题标题】:Insert multiple rows with one select一键插入多行
【发布时间】: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


【解决方案1】:

有一百万种方法可以做到这一点,但如果你想使用子句VALUES 来收集chapters,你可以尝试使用CTE

WITH j (chapter_title) AS (
  VALUES ('fist chapter'),('second chapter')
) 
INSERT INTO chapter (book_id , title) 
SELECT book.id, j.chapter_title FROM j,book
WHERE book.title = 'foo bar';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-13
    • 1970-01-01
    • 1970-01-01
    • 2011-10-17
    • 2021-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多