MySQL:如何为另一个查询的每个id在一个表中插入多行?

时间:2014-02-06 10:10:25

标签: mysql

我有一个键值表,我需要从另一个表中为每个选定的id插入多行。

  1. 我收到了用户ID:

    SELECT @id := id FROM user WHERE email = 'my@email.com';
    
  2. 我按用户ID获取了ID:

    SELECT @things := id FROM `things` WHERE `owner_id` = @id;
    
  3. 现在我需要为每个@things在键值表中插入多个值。这里的问题是我不能使用select子查询,因为我需要插入内联值,如:

    INSERT INTO key_value (key, value)
    VALUES (
        @things, 'CUSTOM VALUE 1'
    ),
    VALUES (
        @things, 'CUSTOM VALUE 2'
    );
    
  4. 但是,它不起作用。最后一个查询显然是错误的。任何帮助将不胜感激。


    编辑:

    看起来我需要多个查询来执行此操作:

    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
    );
    

1 个答案:

答案 0 :(得分:1)

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'