mysql过程:结果由带有select语句的多行组成

时间:2018-12-25 11:21:54

标签: mysql sql procedure

我正在为我的常规重复工作创建一个程序。

在其中,有一个步骤可以将一个表中的多行插入临时表中。

CREATE TABLE `tmpUserList` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `user_type` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
      `first_name` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
      `last_name` varchar(45) COLLATE utf8_unicode_ci NOT NULL
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

    ..... some more queries.


        INSERT INTO  tmpUserList ( 
                SELECT  id, user_type,first_name,last_name,  from user  where  id in  (usersId) 
        );


    SELECT * FROM tmpUserList; // return the result

但是它给了我错误:结果包含多于一行

1 个答案:

答案 0 :(得分:1)

正确的INSERT SELECT语法:

INSERT INTO tmpUserList(id, user_type,first_name,last_name)
SELECT id, user_type,first_name,last_name 
FROM user  
WHERE id IN (usersId);

如果usersId包含多个值,则可以使用:

WHERE FIND_IN_SET(id, usersId);  -- table scan

相关:MySQL Prepared statements with a variable size variable list