返回多个 id 后插入连接 table

Insert into junction table after returning multiple id's

我有一个 Postgresql 数据库,其中包含构成多对多关系的三个表,articleauthorarticle_authors。我有一个基于 this 问题的查询,如果记录不存在,则插入到 articleauthor,如果记录不存在,则插入到 returns 和 id存在,它 returns id 无论如何:

WITH article_s AS (
    SELECT id 
    FROM article 
    WHERE id = 25
),
article_i AS (
    INSERT INTO article 
    (id, web_id, article_title, pub_date, publishers_id)
    SELECT 25, 'world/2013', 'a_title', '2015-07-07T21:58:28Z', 1
    WHERE NOT EXISTS (SELECT 1 FROM article_s)
    RETURNING id
),
author_s AS (
    SELECT id
    FROM author
    WHERE id = 34),
author_i AS(
    INSERT INTO author (id, name)
    SELECT 34, 'an_author'
    WHERE NOT EXISTS (select 1 from author_s)
    RETURNING id
)
SELECT article_i.id, author_i.id 
FROM article_i, author_i
UNION ALL
SELECT article_s.id, author_s.id 
FROM article_s, author_s;

我现在需要将返回的 ID 插入 article_authors,但不确定如何访问返回的 ID 来执行此操作。这是可能的,还是有更优雅的方法来解决这个问题?提前致谢!

为了后代,我是这样解决的:

WITH article_s AS (
    SELECT id
    FROM article
    WHERE id = 3
),
article_i AS(
    INSERT INTO article (id, web_id, article_title, pub_date, publishers_id)
    SELECT 3, 'world/2013', 'Queen hangs andrew', '2015-07-07T21:58:28Z', 1
    WHERE NOT EXISTS (SELECT 1 FROM article_s)
    RETURNING id
),
author_s AS (
    SELECT id
    FROM author
    WHERE id = 1
),
author_i AS (
    INSERT INTO author (id, name)
    SELECT 1, 'Bill Bryson'
    WHERE NOT EXISTS (select 1 from author_s)
    RETURNING id
)
INSERT INTO article_authors (article_id, author_id)
SELECT article_i.id, author_i.id 
FROM article_i, author_i
UNION ALL
SELECT article_s.id, author_s.id 
FROM article_s, author_s;

[未测试] 我认为您可以使用 COALESCE() 加上笛卡尔乘积,因为 _i 和 _s CTS 是互斥的:

WITH article_s AS (
    SELECT id
    FROM article
    WHERE id = 3
),
article_i AS(
    INSERT INTO article (id, web_id, article_title, pub_date, publishers_id)
    SELECT 3, 'world/2013', 'Queen hangs andrew', '2015-07-07T21:58:28Z', 1
    WHERE NOT EXISTS (SELECT 1 FROM article_s)
    RETURNING id
),
author_s AS (
    SELECT id
    FROM author
    WHERE id = 1
),
author_i AS (
    INSERT INTO author (id, name)
    SELECT 1, 'Bill Bryson'
    WHERE NOT EXISTS (select 1 from author_s)
    RETURNING id
)
INSERT INTO article_authors (article_id, author_id)
SELECT COALESCE(article_i.id, article_s.id)
, COALESCE(author_i.id , author_s.id)
FROM article_i, author_i 
  , article_s, author_s -- this is ugly
   ;