MySql - 为另一张表的每个ID插入一行

21

我相信这很简单,只是我无法得到正确的搜索词以找到答案。 但我有一个包含ID的位置表。

ID| Name

1 | Foo

2 | Bar

3 | Blah

还有一张表(table2),其中有一个字段引用了那些位置ID:

ID| LocationID | Foo | Bar

1 | 1          | ... | ...

2 | 2          | ..

3 | 5          | ...

当 LocationId = location 中的一个值时,我想要做的是对另一张表中的每个 ID 添加一条记录。例如:

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

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

48
你可以使用INSERT INTO ... SELECT,所以对于你的例子:
INSERT INTO table2 (locationID, foo, bar) SELECT ID, 'hello', 'world' FROM table1

哦,好的,我也尝试过这样的方法,但我发现“Select ID, 'Hello', 'world'”是在尝试从第一个表中选择这三个值,而不仅仅是ID。 - DasBeasto
SELECT ID, 'hello', 'world' 可能看起来有点奇怪,但它选择了列 ID 和纯文本值 'hello' 和 'world'。您可以通过执行 SELECT ID, 'hello', 'world' FROM table1(即没有 INSERT INTO 部分)来自行查看将要插入的内容。 - Peter van der Wal

2
您可以使用“插入...选择”命令。
Insert Table2 (LocationID, Foo, Bar)
Select ID, "Hello", "World"
From Location

改用“Insert into”而不是仅使用“Insert”,并省略“values”。 - Peter van der Wal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接