首页 > 解决方案 > 从mysql 5.7中的变量将多行插入表中

问题描述

这是我的问题。我有以下存储过程,其中我传递了变量“session_ids”,它实际上是一组值(“1”、“2”、“3”、...、“n”)。我如何将这些值中的每一个传递到临时表的相应行数中?例如,第 1 行的值为“1”,第 2 行的值为“2”,...,第 n 行的值为“n”。

实际上,我想动态地执行此操作,因为我不知道变量“session_ids”中值的数量。我有这个想法,但它不起作用。

PROCEDURE `migrate_session_ids`(IN session_ids LONGTEXT)
CREATE TEMPORARY TABLE tempTable (id INT NOT NULL AUTO_INCREMENT, session_id BIGINT, PRIMARY KEY (`id`)); 
INSERT INTO tempTable(session_id) SELECT * FROM session_ids;

先感谢您

标签: mysqlsqlstored-proceduressql-insertrecursive-query

解决方案


如果您正在运行 MySQL 8.0,则一种选择是使用递归查询来拆分分隔字符串:

delimiter //
create procedure migrate_session_ids(in session_ids longtext)
begin

    create temporary table temptable (
        id int not null auto_increment, 
        session_id bigint, 
        primary key (id)
    );

    insert into temptable(session_id)
    with recursive all_ids as (
        select 
            0 + substring(concat(session_ids, ','), 1, locate(',', concat(session_ids, ',')) -1) id,
            substring(concat(session_ids, ','), locate(',', concat(session_ids, ',')) + 1) rest
        union all
        select 
            0 + substring(rest, 1, locate(',', rest) - 1),
            substring(rest, locate(',', rest) + 1) 
        from all_ids
        where locate(',', rest) > 0
    )
    select id from all_ids;

end//

DB Fiddle 上的演示

call migrate_session_ids('1,4,7');
select * from temptable;

| id  | session_id |
| --- | ---------- |
| 1   | 1          |
| 2   | 4          |
| 3   | 7          |

推荐阅读