Here's a simplified version of a query I'm trying to write. It's intended to save a row as a variable combine, then UPDATE the media_hashtags table if a specific entry exists, else INSERT that entry.
WITH
combine AS (
SELECT * FROM hashtags WHERE hashtag_text='HOPPA'
)
UPDATE media_hashtags SET hashtag_id = (SELECT id FROM combine) WHERE user_id = 58 AND media_id=161;
INSERT INTO media_hashtags (media_id, user_id, hashtag_id)
SELECT 161, 58, (SELECT id FROM combine)
WHERE NOT EXISTS (
SELECT * FROM media_hashtags
WHERE (
user_id = 58 AND
media_id = 161
)
)
RETURNING *
However, I get this error:
ERROR: relation "combine" does not exist
LINE 8: SELECT 161, 58, (SELECT id FROM combine)
Interestingly, If I do a query with only the UPDATE or only the INSERT commands, then it executes as expected. The error only occurs when I do both at once. Any ideas on what the problem is, and a fix?
combinefrom the first