I have a Postgresql database with three tables making up a many-to-many relationship, article
, author
and article_authors
. I have a query based on this question which inserts to article
and author
if the record doesn't exist and returns the id
, and if it does exist, it returns the id
anyway:
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;
I now need to insert the returned ID
's into article_authors
but not really sure how to access the returned ID
's to do this. Is this possible, or is there a more elegant way of solving this problem? Thanks in advance!