我有一个Postgresql数据库,其中有三个表构成多对多关系,article
,author
和article_authors
。我有一个基于this问题的查询,如果记录不存在则返回article
和author
并返回id
,如果确实存在,则返回无论如何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
来执行此操作。这是可能的,还是有更优雅的方法来解决这个问题?提前谢谢!
答案 0 :(得分:2)
[未经测试]我认为您可以使用COALESCE()加上一个carthesian产品,因为_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
;
答案 1 :(得分:0)
对后人来说,这就是我解决它的方式:
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;