MySQL: Insert one row for each key in foreign table for each distinct value in table

MySQLsql

table1:

col1  |  col2
-------------
0      value1
1      value1
2      value1

0      value2
1      value2

2      value3

primary key is col1 and col2 together

table2:

col1  | col3
-------------
0      name1
1      name2
2      name3

primary key is col1.
col1 in table1 is referring to col1 in table2.

I need a mysql query that goes through each distinct col2 in table1 and INSERTS one column for each col1 in table2 if the col1 + col2 keypair doesn't already exist.

So basically after this query is run table2 should look the same and table1 should look like this:

col1  |  col2
-------------
0      value1
1      value1
2      value1

0      value2
1      value2
2      value2

0      value3
1      value3
2      value3

I know how to do this with a loop in php but I'm trying to get away from that learning more sql.

Best Answer

INSERT IGNORE INTO `table1`
SELECT DISTINCT `table2`.`col1`, `table1`.`col2`
FROM `table1`
JOIN `table2`