简体   繁体   中英

MySql - Insert row for each ID of other table

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..

你可以使用INSERT INTO ... SELECT ,所以为你的例子

INSERT INTO table2 (locationID, foo, bar) SELECT ID, 'hello', 'world' FROM table1

You can do an Insert... Select

Insert Table2 (LocationID, Foo, Bar)
Select ID, "Hello", "World"
From Location

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM