mysql - 从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;
先感谢您
解决方案
如果您正在运行 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 |
推荐阅读
- python - 将切片与索引混合到 NumPy 中的 mgrid 输入
- flutter - 想防止我的输出飞镖被剪裁
- javascript - 当它在第一页时如何获得分页的活动类?
- javascript - 使用 webdriver io 的 javascript 移动自动化
- python - 使用 python-requests 保存 csv 文件时,有人可以帮助解决 Pandas 错误吗?
- android - 使用 Retrofit 在同一屏幕中调用两个不同的端点
- ios - Git 克隆在 Windows-Flutter、iOS 上失败
- ffmpeg - 使用 ffmpeg 指定 .aac 的输入持续时间
- google-apps-script - 发布文件 GAS
- javascript - Javascript:无法设置属性样式不透明度,TypeError:无法读取未定义的属性“样式”