find_in_set 函數(shù)的語法:
FIND_IN_SET(str,strList)
- str 要查詢的字符串
- strList 字段名,參數(shù)以“,”分隔,如(1,2,6,8)
- 查詢字段(strList)中包含的結(jié)果,返回結(jié)果null或記錄。
假如字符串str在由N個子鏈組成的字符串列表strlist 中,則返回值的范圍在 1 到 N 之間。 一個字符串列表就是一個由一些被 ‘,’ 符號分開的子鏈組成的字符串。如果第一個參數(shù)是一個常數(shù)字符串,而第二個是type SET列,則FIND_IN_SET() 函數(shù)被優(yōu)化,使用比特計算。 如果str不在strlist 或strlist 為空字符串,則返回值為 0 。如任意一個參數(shù)為NULL,則返回值為 NULL。這個函數(shù)在第一個參數(shù)包含一個逗號(‘,’)時將無法正常運行。
例子一 基礎(chǔ)用法
1
select find_in_set('1','1,2,3,4,5,6');
2
select find_in_set('2','1,2,3,4,5,6');
0
select find_in_set('7','1,2,3,4,5,6');
0
select find_in_set('2','1,21,3,4,5,6');
0
select find_in_set('1','');
null
select find_in_set(null,'1,2,3,4,5,6');
null
select find_in_set('1',null);
例子二 find_in_set()和in的區(qū)別
創(chuàng)建表,并添加數(shù)據(jù)
CREATE TABLE `tb_test` (
`id` int(8) NOT NULL auto_increment,
`name` varchar(255) NOT NULL,
`list` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO `tb_test` VALUES (1, 'name', 'daodao,xiaohu,xiaoqin');
INSERT INTO `tb_test` VALUES (2, 'name2', 'xiaohu,daodao,xiaoqin');
INSERT INTO `tb_test` VALUES (3, 'name3', 'xiaoqin,daodao,xiaohu');
查詢一
SELECT * from tb_test where "daodao" in (list);
結(jié)果
解析:
實際上這樣是不行的,這樣只有當list字段的值等于'daodao'時(和IN前面的字符串完全匹配),查詢才有效,否則都得不到結(jié)果,即使'daodao'真的在list中。
SELECT * from tb_test where "daodao,xiaohu,xiaoqin" in (list);
執(zhí)行上面這條語句,才能返回結(jié)果。
查詢二
SELECT * from tb_test WHERE 'daodao' IN ('libk', 'zyfon', 'daodao')
結(jié)果
解析:
這兩條到底有什么區(qū)別呢?為什么第一條不能取得正確的結(jié)果,而第二條卻能取得結(jié)果。原因其實是(一)中 (list) list是變量, 而(二)中 ('libk', 'zyfon', 'daodao')是常量。
查詢?nèi)?/strong>
SELECT * from tb_test where FIND_IN_SET("daodao",list)
結(jié)果
解析:
find_in_set 函數(shù) 這里的“l(fā)ist” 是 變量
例子三 find_in_set()和like的區(qū)別
在mysql中,有時我們在做數(shù)據(jù)庫查詢時,需要得到某字段中包含某個值的記錄,但是它也不是用like能解決的,使用like可能查到我們不想要的記錄,它比like更精準,這時候mysql的FIND_IN_SET函數(shù)就派上用場了
創(chuàng)建表,并插入數(shù)據(jù)
CREATE TABLE users(
id int(6) NOT NULL AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
limits VARCHAR(50) NOT NULL, -- 權(quán)限
PRIMARY KEY (id)
);
INSERT INTO users(name, limits) VALUES('小張','1,2,12');
INSERT INTO users(name, limits) VALUES('小王','11,22,32');
其中l(wèi)imits表示用戶所擁有的權(quán)限(以逗號分隔),現(xiàn)在想查詢擁有權(quán)限編號為2的用戶,如果用like關(guān)鍵字的話,則查詢結(jié)果如下:
SELECT * FROM users WHERE limits LIKE '%2%';
很顯然,結(jié)果不符合預(yù)期,下面用find_in_set 函數(shù) 來 解決。
SELECT * from users where FIND_IN_SET('2',limits)
解析:
mysql字符串函數(shù) find_in_set(str1,str2)函數(shù)是返回str2中str1所在的位置索引,str2必須以","分割開。
總結(jié):like是廣泛的模糊匹配,字符串中沒有分隔符,F(xiàn)ind_IN_SET 是精確匹配,字段值以英文”,”分隔,F(xiàn)ind_IN_SET查詢的結(jié)果要小于like查詢的結(jié)果。
例子四
select t.id from
(
select 1 as id, 'nick' as name
union all
select 2 as id, 'viki' as name
union all
select 3 as id, 'robin' as name
union all
select 4 as id, 'teng' as name
union all
select 5 as id, 'mike' as name
union all
select 6 as id, 'will' as name
) t
where find_in_set(t.id, '2,3,4') > 0;
結(jié)果
參考文獻:https://blog.csdn.net/chenpeng19910926/article/details/51790034
https://blog.csdn.net/c_base_jin/article/details/74358235