Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

postgresql - Get serial PK from row created in 1st query to query another table

I want to add a row to my table recipes, and based on the PK that gets created for that row in my first query, need to update my bridge table recipe_technology. Unfortunately I cannot access my newly created id, probably bc I am not returning anything from the insert statement. The below query does what I want it to do when I hardcode the id ("SELECT 1 id"), but otherwise I am a bit clueless what to do. Any leads would be much appreciated!

WITH query_one AS (
 INSERT INTO (a, b, c) VALUES ($1, $2, $3)
) 
INSERT INTO recipe_technology(recipe_id, technology_id) 
SELECT 1 id, x FROM unnest(ARRAY[1,2,3]) x`,[a,b,c]
question from:https://stackoverflow.com/questions/66052530/get-serial-pk-from-row-created-in-1st-query-to-query-another-table

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
WITH query_one(newid) AS 
(
 INSERT INTO (a, b, c) VALUES ($1, $2, $3) returning id
) 
INSERT INTO recipe_technology(recipe_id, technology_id) 
SELECT newid, x FROM query_one, unnest(ARRAY[1,2,3]) t(x);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...