Sorry for the followup question (from INSERT into table if doesn't exists and return id in both cases)
But I couldn't find any solution for my questions.
I have a feedback table whose columns are foreign key of other tables. For ex. scopeid is foregin key of id column in scope table, similarly userid is foreign key of id column from user table and so on.
So, I am trying to insert following data in the table: scope: home_page, username: abc status: fixed app: demoapp
So, to insert above data, I am trying to write subquery to get the id of each value and use that. Also if that value doesn't exists insert and use the new ID to insert that in feedback table.
So basically I am trying to insert into multiple table (if something doesnt exists) and use those ID to insert into final table which is feedback table.
Hope things are much clearer now.
Here is my feedback table:
id scopeid comment rating userid statusid appid
3 1 test 5 2 1 2
All the id columns are foreign key of other tables and so in my below query I am trying to get the id by name and if not exists add those.
Here is my final query:
INSERT INTO feedbacks (scopeid, comment, rating, userid, statusid, appid)
VALUES
(
-- GET SCOPE ID
(
WITH rows_exists AS (
SELECT id FROM scope
WHERE appid=2 AND NAME = 'application'),
row_new AS (INSERT INTO scope (appid, NAME) SELECT 2, 'application' WHERE NOT EXISTS (SELECT id FROM scope WHERE appid=2 AND name='application') returning id)
SELECT id FROM rows_exists UNION ALL SELECT id FROM row_new
),
-- Comment
'GOD IS HERE TO COMMENT',
-- rating
5,
-- userid
(
WITH rows_exists AS (
SELECT id FROM users
WHERE username='abc'),
row_new AS (INSERT INTO users (username) SELECT 'abc' WHERE NOT EXISTS (SELECT id FROM users WHERE username='abc') returning id)
SELECT id FROM rows_exists UNION ALL SELECT id FROM row_new
),
-- statusid
(SELECT id FROM status WHERE NAME='received'),
-- appid
(
WITH rows_exists AS (
SELECT id FROM apps
WHERE name='google'),
row_new AS (INSERT INTO apps (name) SELECT 'google' WHERE NOT EXISTS (SELECT id FROM apps WHERE NAME='google') returning id)
SELECT id FROM rows_exists UNION ALL SELECT id FROM row_new
)
)
But I get following Error:
with clause containing a data-modifying statement must be at the top level
Is that even possible what I am trying to achieve by this way or other method.
insertin a CTE if it is the first CTE in the query.INSERTinto feedbacks or multiple inserts into other tables? How does scope, user, status, and apps relate? Please back up and give a fuller description of your XY problem.