MySQL 没有提供 split 函数,但可以自己建立一个存储过程,将具有固定分隔符的字符串转成多行。之所以不能使用自定义函数实现此功能,是因为 MySQL 的自定义函数自能返回标量值,不能返回多行结果集。
MySQL 8:
drop procedure if exists sp_split;
delimiter //
create procedure sp_split(p_str text, p_delimiter varchar(100))
begin
select substring_index(substring_index(p_str, p_delimiter, lv), p_delimiter, - 1) a
from (
with recursive tab1(lv) as (
select 1 lv
union all
select t1.lv + 1 from tab1 t1
where lv < (char_length(p_str) - char_length(replace(p_str, p_delimiter, ''))) / (char_length(p_delimiter)) + 1)
select * from tab1
) t1;
end;
//
delimiter ;
MySQL 5:
drop procedure if exists sp_split;
delimiter //
create procedure sp_split(p_str text, p_delimiter varchar(100))
begin
select substring_index(substring_index(p_str, p_delimiter, help_topic_id + 1), p_delimiter, - 1) a
from mysql.help_topic
where help_topic_id < (char_length(p_str) - char_length(replace(p_str, p_delimiter, ''))) / (char_length(p_delimiter)) + 1;
end;
//
delimiter ;
测试:
mysql> set @a:='123,456,789';
Query OK, 0 rows affected (0.00 sec)
mysql> call sp_split(@a,',');
+------+
| a |
+------+
| 123 |
| 456 |
| 789 |
+------+
3 rows in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
mysql> set @a:='中;;English;;混杂;;多字符分隔符';
Query OK, 0 rows affected (0.00 sec)
mysql> call sp_split(@a,';;');
+--------------------+
| a |
+--------------------+
| 中 |
| English |
| 混杂 |
| 多字符分隔符 |
+--------------------+
4 rows in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)