使用Selected数据执行多次插入

时间:2014-10-03 10:33:13

标签: mysql sql

我想执行这个sudo查询:

INSERT INTO table1 (foreign_key, meta_key, meta_value)
VALUES (
     (SELECT id FROM table2 WHERE condition = 'met'), 'first meta key', 'first meta value'
)
VALUES (
     (SELECT id FROM table2 WHERE condition = 'met'), 'second meta key', 'second meta value'
)
VALUES (
     (SELECT id FROM table2 WHERE condition = 'met'), 'third meta key', 'third meta value'
)

SELECT语句后面的字符串是INSERT

的第二和第三个参数

我认为INSERT SELECT syntex基本上是正确的,但我不确定多重INSERTS。我知道我可以使用正常的INSERT语句这样做,但我不确定SELECT条款中的VALUES

我正在使用实时数据库,虽然我已经支持所有内容,但我希望将直接实验保持在最低限度。

2 个答案:

答案 0 :(得分:1)

你可以使用UNION:

INSERT INTO table1 (foreign_key, meta_key, meta_value)
SELECT id, 'first meta key', 'first meta value' FROM table2 WHERE condition = 'met'
UNION
SELECT id, 'second meta key', 'second meta value' FROM table2 WHERE condition = 'met'
UNION
SELECT id, 'third meta key', 'third meta value' FROM table2 WHERE condition = 'met'

答案 1 :(得分:1)

您需要在值之间添加逗号。

INSERT INTO table1 (foreign_key, meta_key, meta_value)
VALUES (
     (SELECT id FROM table2 WHERE condition = 'met'), 'first meta key', 'first meta value'
),
(
     (SELECT id FROM table2 WHERE condition = 'met'), 'second meta key', 'second meta value'
),
(
     (SELECT id FROM table2 WHERE condition = 'met'), 'third meta key', 'third meta value'
)

并确保每个子查询仅返回1行。

试试这个Sql Fiddle Demo

或者以正常的方式使用union:

INSERT INTO table1 (foreign_key, meta_key, meta_value)
SELECT id, 'first meta key' , 'first meta value'  FROM table2 WHERE condition = 'met')
UNION ALL
SELECT id, 'second meta key', 'second meta value' FROM table2 WHERE condition = 'met')
UNION ALL
SELECT id, 'third meta key' , 'third meta value'  FROM table2 WHERE condition = 'met')