Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql - Insert row for each ID of other table

Tags:

mysql

I'm sure this is simple I just cant get the correct search terms to find the answer. But I have one table for locations with IDs

ID| Name

1 | Foo

2 | Bar

3 | Blah

and another table (table2) that has a field referencing those location IDs:

ID| LocationID | Foo | Bar

1 | 1          | ... | ...

2 | 2          | ..

3 | 5          | ...

Where LocationId = a value from location. What I want to do is for every ID in location (1,2,3...) add a record to the other table. So for example:

"insert into table2 (locationID, foo, bar) values (1, "hello", "world");"

"insert into table2 (locationID, foo, bar) values (2, "hello", "world");"

and so on..

like image 369
DasBeasto Avatar asked Jul 22 '14 18:07

DasBeasto


1 Answers

You can use INSERT INTO ... SELECT, so for your example

INSERT INTO table2 (locationID, foo, bar) SELECT ID, 'hello', 'world' FROM table1
like image 100
Peter van der Wal Avatar answered Sep 20 '22 18:09

Peter van der Wal