mysql split函数用逗号分隔的实现
程序员文章站
2022-03-11 09:12:34
1:定义存储过程,用于分隔字符串delimiter $$use `mess`$$drop procedure if exists `splitstring`$$create definer=`root...
1:定义存储过程,用于分隔字符串
delimiter $$ use `mess`$$ drop procedure if exists `splitstring`$$ create definer=`root`@`%` procedure `splitstring`(in f_string varchar(1000),in f_delimiter varchar(5)) begin declare cnt int default 0; declare i int default 0; set cnt = func_get_splitstringtotal(f_string,f_delimiter); drop table if exists `tmp_split`; create temporary table `tmp_split` (`val_` varchar(128) not null) default charset=utf8; while i < cnt do set i = i + 1; insert into tmp_split(`val_`) values (func_splitstring(f_string,f_delimiter,i)); end while; end$$ delimiter ;
2:实现func_get_splitstringtotal函数:该函数用于计算分隔之后的长度,这里需要了解的函数:
replace(str,from_str,to_str) returns the string str with all occurrences of the string from_str replaced by the string to_str. replace() performs a case-sensitive match when searching for from_str. 例如: mysql> select replace('www.mysql.com', 'w', 'ww'); -> 'wwwwww.mysql.com'
具体实现:
delimiter $$ use `mess`$$ drop function if exists `func_get_splitstringtotal`$$ create definer=`root`@`%` function `func_get_splitstringtotal`( f_string varchar(10000),f_delimiter varchar(50) ) returns int(11) begin return 1+(length(f_string) - length(replace(f_string,f_delimiter,''))); end$$ delimiter ;
3:实现func_splitstring函数:用于获取分隔之后每次循环的值,这里需要了解的函数:
(1)reverse(str) returns the string str with the order of the characters reversed. 例如:mysql> select reverse('abc'); -> 'cba' (2) substring_index(str,delim,count) returns the substring from string str before count occurrences of the delimiter delim. if count is positive, everything to the left of the final delimiter (counting from the left) is returned. if count is negative, everything to the right of the final delimiter (counting from the right) is returned. substring_index() performs a case-sensitive match when searching for delim. 例如: mysql> select substring_index('www.mysql.com', '.', 2); -> 'www.mysql' mysql> select substring_index('www.mysql.com', '.', -2); -> 'mysql.com'
具体实现:
delimiter $$ use `mess`$$ drop function if exists `func_splitstring`$$ create definer=`root`@`%` function `func_splitstring`( f_string varchar(1000),f_delimiter varchar(5),f_order int) returns varchar(255) charset utf8 begin declare result varchar(255) default ''; set result = reverse(substring_index(reverse(substring_index(f_string,f_delimiter,f_order)),f_delimiter,1)); return result; end$$ delimiter ;
使用:
(1)调用存储过程:
call splitstring('1,3,5,7,9',',');
(2):查看临时表
select val_ from tmp_split as t1;
结果:
到此这篇关于mysql split函数用逗号分隔的实现的文章就介绍到这了,更多相关mysql split逗号分隔内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: AFNetworking之小试牛刀
下一篇: vs code编辑器的设置json文件
推荐阅读