下面两个函数的使用和FIND_IN_SET
一样,使用时只需要把FIND_IN_SET
换成FIND_PART_IN_SET
或FIND_ALL_PART_IN_SET
例如某字段里是为1,2,3,4,5
使用方法:
第一种,传入1,3,6 可以查出来
1
|
select * from XXX where FIND_PART_IN_SET( '1,3,6' , '1,2,3,4,5' ) |
第二种,传入1,3,6 查不出来
1
|
select * from XXX where FIND_ALL_PART_IN_SET( '1,3,6' , '1,2,3,4,5' ) |
函数:
第一种:只要包含其中一个就可以被查出来
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
CREATE DEFINER = `root`@`%` FUNCTION `NewProc`(str1 text,str2 text) RETURNS text BEGIN 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 ; |
第二种:必须全部包含才可以被查出来
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
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逗号拼接字符串查询的两种方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
原文链接:https://blog.csdn.net/guochanof/article/details/98944379