简体   繁体   English

MySql - 为其他表的每个ID插入行

[英]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的位置

ID| Name

1 | Foo

2 | Bar

3 | Blah

and another table (table2) that has a field referencing those location IDs: 和另一个表(table2),其中有一个引用这些位置ID的字段:

ID| LocationID | Foo | Bar

1 | 1          | ... | ...

2 | 2          | ..

3 | 5          | ...

Where LocationId = a value from location. 其中LocationId =来自位置的值。 What I want to do is for every ID in location (1,2,3...) add a record to the other table. 我想要做的是为位置中的每个ID(1,2,3 ......)添加一个记录到另一个表。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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