这是我的问题。我有以下存储过程,其中我传递了变量'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;
先谢谢你
如果你运行的是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//
call migrate_session_ids('1,4,7');
select * from temptable;
| id | session_id |
| --- | ---------- |
| 1 | 1 |
| 2 | 4 |
| 3 | 7 |
在我的情况下,它没有工作recuring查询,因为我运行MySQL 5.7,我很困惑与解决方案(转换)在网络上这个MySQL版本.So,最后我想出了一个解决方案,使用'concat'和动态查询这样的,并希望分享它,以防止有人面临类似的问题。
SET @sql = concat('INSERT INTO tempTable(session_id) SELECT id_session FROM Notes WHERE id_session IN (',session_ids,')');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;