![](/img/trans.png)
[英]How can I insert multiple rows into one table, then into another table using an auto incremented ID? mysql
[英]MySQL: How to insert multiple rows into one table for each id of another query?
我有一个键值表,我需要为另一个表中的每个选定id
插入多行。
我得到用户ID:
SELECT @id := id FROM user WHERE email = 'my@email.com';
我通过用户ID获得事物的ID:
SELECT @things := id FROM `things` WHERE `owner_id` = @id;
现在,我需要为每个@things
插入多个值到键值表中。 这里的问题是我不能使用选择子查询,因为我需要插入内联值,例如:
INSERT INTO key_value (key, value) VALUES ( @things, 'CUSTOM VALUE 1' ), VALUES ( @things, 'CUSTOM VALUE 2' );
但是,它不起作用。 最后一个查询显然是错误的。 任何帮助将非常感激。
看来我需要多个查询才能做到这一点:
SELECT @id := id FROM user WHERE email = 'startour@netron.no';
INSERT INTO key_value (`key`, `value`)
(
SELECT id, 'CUSTOM_VALUE_1'
FROM `things`
WHERE `owner_id` = @id
);
INSERT INTO key_value (`key`, `value`)
(
SELECT id, 'CUSTOM_VALUE_2'
FROM `things`
WHERE `owner_id` = @id
);
INSERT INTO key_value (key, value)
SELECT user.id as key, things.id as value FROM user
left outer join things on user.id=things.owner_id
WHERE user.email = 'my@email.com'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.