Reputation: 1485
I have two tables connected with one to many relationship.
Parent Table is a simple user table with id and first_name column
Parent
id | first_name
1 | Bob
2 | Dick
3 | Harry
4 | Tom
5 | Holly
Child Table contains insurance selection for a user.
Child
id | insu_id | user_id | year
1 | 188765 | 1 | 2008
2 | 188765 | 1 | 2009
3 | 188765 | 1 | 2010
4 | 188765 | 1 | 2011
5 | 188765 | 1 | 2012
I want to copy insurance selection of user_id
1 to all rest of the users i.e. 2, 3, 4, 5 in child table so that the table should look like
id | insu_id | user_id | year
1 | 188765 | 1 | 2008
2 | 188765 | 1 | 2009
3 | 188765 | 1 | 2010
4 | 188765 | 1 | 2011
5 | 188765 | 1 | 2012
6 | 188765 | 2 | 2008
7 | 188765 | 2 | 2009
8 | 188765 | 2 | 2010
9 | 188765 | 2 | 2011
10 | 188765 | 2 | 2012
11 | 188765 | 3 | 2008
12 | 188765 | 3 | 2009
13 | 188765 | 3 | 2010
14 | 188765 | 3 | 2011
15 | 188765 | 3 | 2012
16 | 188765 | 4 | 2008
17 | 188765 | 4 | 2009
18 | 188765 | 4 | 2010
19 | 188765 | 4 | 2011
20 | 188765 | 4 | 2012
21 | 188765 | 5 | 2008
22 | 188765 | 5 | 2009
23 | 188765 | 5 | 2010
24 | 188765 | 5 | 2011
25 | 188765 | 5 | 2012
What Can I do
INSERT INTO child(insurance_id, user_id, year) SELECT insurance_id, '2', year FROM child WHERE user_id = 1
INSERT INTO child(insurance_id, user_id, year) SELECT insurance_id, '3', year FROM child WHERE user_id = 1
INSERT INTO child(insurance_id, user_id, year) SELECT insurance_id, '4', year FROM child WHERE user_id = 1
INSERT INTO child(insurance_id, user_id, year) SELECT insurance_id, '5', year FROM child WHERE user_id = 1
What I want
I don't want to run 4 different INSERT INTO() SELECT
queries because number of users can increase beyond that. I want one query selecting user_id dynamically rather than hard coding.
Upvotes: 1
Views: 661
Reputation: 4045
I have tried that and it seems to work. I get the insurance data from child table for the first user and join it with all other users in the parent table in order to insert the result. You may have to fix the column names if they are not the same as your database.
INSERT INTO child(insurance_id, user_id, year)
SELECT a.insurance_id, b.id, a.year
FROM
child a, parent b
WHERE a.user_id = 1 AND b.id > 1
ORDER BY b.id, a.year
This will always insert insurance data for all users except the one with id = 1. No matter how many of them you have. Hope that helps :)
Upvotes: 2