Created
July 9, 2012 13:28
-
-
Save mmalmeida/3076560 to your computer and use it in GitHub Desktop.
Postgresql complex insert into
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Consider the model: | |
| car | |
| |id|code|Model name| | |
| |1|100|Deluxe| | |
| |10|100|Deluxe improved| | |
| color | |
| |id|Name| | |
| |2|Red| | |
| car_colors | |
| |id|car_id|color_id| | |
| |3|1|2| | |
| The deluxe car was added, and afterwards the "deluxe improved" model was inserted. It's a new version of the same car (same code). Unfortunately, John Doe forgot to update the car_colors table, so now you want to update that table by inserting the same colors for "Deluxe improved" as there existed for the "Deluxe" model. | |
| The PSEUDO-CODE (non-sql) should be something like: | |
| all_cars_and_colors = select * from car left outer join car_colors | |
| for each(this_car:all_cars_and_colors){ | |
| if(all_cars_and_colors.color_id does not exist){ | |
| car_colors_to_copy = select * from car inner join car_colors where car.code=this_car.code | |
| for each(color_to_copy: car_colors_to_copy){ | |
| insert into car_colors(id,car_id,color_id) VALUES (nextval('id_sequence') ,this_car.id,color_to_copy.color_id) | |
| } | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment