Mysql 逗号分隔行列转换总结

方法一
存储过程实现:

-- 修改结束符,防止在mysql命令行中默认分号直接运行
delimiter $$

-- 创建一个计算拆分后字符串的个数函数
drop function if exists calc_length $$
create function calc_length(str varchar(200), splitstr varchar(5)) returns int(11)
begin 
return length(str)-length(replace(str, splitstr, ''))+1;
end $$

-- 创建一个模拟的split拆分字符串的函数
drop function if exists split_string $$
create definer='root'@'localhost' function split_string(str varchar(200), splitstr varchar(5), strindex int) returns varchar(255)
begin
declare result varchar(255) default '';
set result =reverse(substring_index( reverse(substring_index(str, splitstr, strindex)), splitstr, 1));
return result;
end $$

-- 创建一个存储过程
drop procedure if exists proce_split $$
create procedure proce_split()
begin
declare cnt int default 0;
declare i int default 0;
declare str varchar(2000) default '';
select name into str from table1 where id =2;
set cnt = calc_length(str, ',');

drop table if exists table2;
create table2(id int not null, name varchar(255) not null) default charset=utf8;

while i < cnt 
do 
set i = i+1;
insert into table(id, name) values(i, split_string(str,',', i));
end while;
end $$

方法二:
笛卡尔积实现:

select a.ID,substring_index(substring_index(a.loginName,',',b.help_topic_id+1),',',-1) 
from 
account a
join
mysql.help_topic  b
on b.help_topic_id < (length(a.loginName)- length(replace(a.loginName,',',''))+1)
order by a.ID;
原文地址:https://www.cnblogs.com/fengyingwang/p/7591221.html