I have a story_id table like this.
Column | Type | Modifiers
--------------+---------+-------------------------------------------------------------------
id | integer | not null default nextval('story_sites_id_seq'::regclass)
story_id | integer | not null
site_id | integer | not null
I want to add new rows with site_id = 12 and story_id which already has site_id = 70 , here is my query, it works well:
INSERT INTO story_sites (story_id, site_id)
SELECT story_id, 12
FROM story_sites
WHERE site_id = 70;
But if there're rows which already has site_id = 12, I'll get a duplicate key error.
So I want to exclude those duplicate rows, here is my new query, however it doesn't work properly, it inserts nothing when I think it should. Also it seems I can't use ON CONFLICT DO NOTHING in Postgres 9.4. How should I do it ?
INSERT INTO story_sites (story_id, site_id)
SELECT story_id, 12
FROM story_sites
WHERE site_id = 70
AND NOT EXISTS
(
SELECT id
FROM story_sites
WHERE site_id = 12
);