推薦 MySQL的FIND_IN_SET()函數html
MySQL存儲過程能夠用於分割字符串,下面就爲您詳細介紹這種MySQL存儲過程的用法,供您參考學習之用。mysql
現有一段字符串,如apple,banana,orange,pears,grape,要把它按照逗號(,)分割成:sql
而後使用where in()方法能夠查詢。app
一、具體函數:函數
# 函數:func_split_TotalLength 學習
DELIMITER $$ 測試
DROP function IF EXISTS `func_split_TotalLength` $$ ui
CREATE DEFINER=`root`@`%` FUNCTION `func_split_TotalLength` url
(f_string varchar(1000),f_delimiter varchar(5)) RETURNS int(11) spa
BEGIN
# 計算傳入字符串的總length
return 1+(length(f_string) - length(replace(f_string,f_delimiter,'')));
END$$
DELIMITER;
# 函數:func_split
DELIMITER $$
DROP function IF EXISTS `func_split` $$
CREATE DEFINER=`root`@`%` FUNCTION `func_split`
(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;
# 存儲過程:splitString
DELIMITER $$
DROP PROCEDURE IF EXISTS `splitString` $$
CREATE 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_split_TotalLength(f_string,f_delimiter);
DROP TABLE IF EXISTS `tmp_split`;
create temporary table `tmp_split` (`status` varchar(128) not null) DEFAULT CHARSET=utf8;
while i < cnt
do
set i = i + 1;
insert into tmp_split(`status`) values (func_split(f_string,f_delimiter,i));
end while;
END$$
DELIMITER;
二、測試是否能成功分割
call splitString("apple,banana,orange,pears,grape",",");
select * from tmp_split;
運行結果以下,說明分割成功:
+--------+ | status | +--------+ | apple | | banana | | orange | | pears | | grape | +--------+ 5 rows in set
mysql>
三、應用where in()查詢
轉 : https://www.cnblogs.com/waban/p/5196267.html
轉 : https://blog.csdn.net/myb0220/article/details/50459797
參考: MySQL的FIND_IN_SET()函數
轉: https://www.cnblogs.com/mytzq/p/7090197.html