Sample Header Ad - 728x90

For each row create a linked row in another table with auto-generated ID

3 votes
2 answers
1775 views
In Postgres, I have an existing table: things | thing_id | thing_name | destination_id | | -------- | ---------- | -------------- | | 10 | thing 10 | null | | 15 | thing 15 | null | For each row in that table, I want to add rows to two new related tables one of which has an auto-generated ID. I then want to update rows in the old table to point to related new rows. Desired result: things | thing_id | thing_name | destination_id | | -------- | ---------- | -------------- | | 10 | thing 10 | 1 | | 15 | thing 15 | 2 | parent_destination | destination_id | | -------------- | | 1 | | 2 | child_destination | destination_id | destination_name | | -------------- | ---------------- | | 1 | [destination] thing 10 | | 2 | [destination] thing 15 | I have tried to do it here: https://www.db-fiddle.com/f/6iyvCT7BYXPHPi2N2HvNor/1 but I can't work out how to return the correct data from result1.
Asked by Robert Elliot (187 rep)
Sep 24, 2022, 12:52 PM
Last activity: Sep 27, 2022, 05:23 AM