MySql逗号拼接字符串查询的两种⽅法
下⾯两个函数的使⽤和FIND_IN_SET⼀样,使⽤时只需要把FIND_IN_SET换成FIND_PART_IN_SET或FIND_ALL_PART_IN_SET 例如某字段⾥是为1,2,3,4,5
使⽤⽅法:
第⼀种,传⼊1,3,6 可以查出来
select * from XXX where FIND_PART_IN_SET('1,3,6','1,2,3,4,5')
第⼆种,传⼊1,3,6 查不出来
select * from XXX where FIND_ALL_PART_IN_SET('1,3,6','1,2,3,4,5')
函数:
第⼀种:只要包含其中⼀个就可以被查出来
CREATE DEFINER = `root`@`%` FUNCTION `NewProc`(str1 text,str2 text)
RETURNS text
BEGIN
#传⼊两个逗号分割的字符串,判断第⼆个字符串是否包含第⼀个字符串split之后的单个
DECLARE CURRENTINDEX INT;#当前下标
DECLARE CURRENTSTR text;
DECLARE result int;
set result = 0;
set CURRENTINDEX = 0;
set CURRENTSTR = '';
IF str1 IS NOT NULL AND str1 != '' THEN
SET CURRENTINDEX = LOCATE(',',str1);
WHILE CURRENTINDEX > 0 DO
SET CURRENTSTR = substring(str1,1,CURRENTINDEX-1);
if FIND_IN_SET(CURRENTSTR,str2) THEN
set result = 1;
end if;
SET str1 = substring(str1,CURRENTINDEX+1);
SET CURRENTINDEX = LOCATE(',',str1);
END WHILE;
#只传⼀个和最后⽆逗号的情况
IF LENGTH(str1) > 0 THEN
if FIND_IN_SET(str1,str2) THEN
set result = 1;
end if;
END IF;
END IF;
RETURN result;
END;
第⼆种:必须全部包含才可以被查出来
CREATE DEFINER = `root`@`%` FUNCTION `NewProc`(str1 text,str2 text)
RETURNS text
BEGIN
#传⼊两个逗号分割的字符串,判断第⼆个字符串是否全部包含第⼀个字符串split之后的单个
DECLARE CURRENTINDEX INT;#当前下标
DECLARE CURRENTSTR text;
DECLARE RESULT int;
DECLARE TOTALCOUNT int;
DECLARE TRUECOUNT int;
set RESULT = 0;
set CURRENTINDEX = 0;
set CURRENTSTR = '';
set TOTALCOUNT = 0;
set TRUECOUNT = 0;
IF str1 IS NOT NULL AND str1 != '' THEN
SET CURRENTINDEX = LOCATE(',',str1);
WHILE CURRENTINDEX > 0 DO
SET TOTALCOUNT = TOTALCOUNT + 1;
SET CURRENTSTR = substring(str1,1,CURRENTINDEX-1);
if FIND_IN_SET(CURRENTSTR,str2) THEN
字符串截取逗号SET TRUECOUNT = TRUECOUNT + 1;
end if;
SET str1 = substring(str1,CURRENTINDEX+1);
SET CURRENTINDEX = LOCATE(',',str1);
END WHILE;
#只传⼀个和最后⽆逗号的情况
IF LENGTH(str1) > 0 THEN
SET TOTALCOUNT = TOTALCOUNT + 1;
if FIND_IN_SET(str1,str2) THEN
SET TRUECOUNT = TRUECOUNT + 1;
end if;
END IF;
END IF;
IF TOTALCOUNT > 0 AND TRUECOUNT = TOTALCOUNT THEN
SET RESULT = 1;
END IF;
RETURN result;
END;
总结
以上所述是⼩编给⼤家介绍的MySql逗号拼接字符串查询的两种⽅法,希望对⼤家有所帮助,如果⼤家有任何疑问请给我留⾔,⼩编会及时回复⼤家的。在此也⾮常感谢⼤家对⽹站的⽀持!
如果你觉得本⽂对你有帮助,欢迎转载,烦请注明出处,谢谢!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论