下面两个函数的使用和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逗号拼接字符串查询的两种方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!