find_in_set函数用于返回字符串str在字符串列表str_list中的位置,返回一个整数或一个null值
语法格式
find_in_set(str,str_list)
str: 需要查询的字符串
str_list: 需要查询的字符串列表,参数以","分隔,形式如 (1,2,6,8,10,22)
提示tips
① 如果在 str_list 中没有找到 str,find_in_set函数返回 0
② 如果 str 或 str_list 为 null,find_in_set函数返回 null
③ 如果 str_list 是一个空字符串(""),find_in_set函数函数返回 0
示例1
-- 1
select find_in_set("a", "a");
-- 3
select find_in_set("c", "a,b,c,c,d");
-- 0
select find_in_set("a", "s,q,l");
-- 0
select find_in_set("q", "");
-- 5
select find_in_set("o", "h,e,l,l,o");
-- null
select find_in_set("q", null);
-- null
select find_in_set(null, "s,q,l");
示例2
导入数据
drop table if exists `divisions`;
create table `divisions` (
`id` int(11) not null auto_increment,
`name` varchar(25) not null,
`belts` varchar(200) not null,
primary key (`id`)
) engine=innodb auto_increment=11 default charset=utf8mb4;
insert into `divisions` values ('1', 'o-1', 'white,yellow,orange');
insert into `divisions` values ('2', 'o-2', 'purple,green,blue');
insert into `divisions` values ('3', 'o-3', 'brown,red,black');
insert into `divisions` values ('4', 'o-4', 'white,yellow,orange');
insert into `divisions` values ('5', 'o-5', 'purple,green,blue');
insert into `divisions` values ('6', 'o-6', 'brown,red');
insert into `divisions` values ('7', 'o-7', 'black');
insert into `divisions` values ('8', 'o-8', 'white,yellow,orange');
insert into `divisions` values ('9', 'o-9', 'purple,green,blue');
insert into `divisions` values ('10', 'o-10', 'brown,red');divisions表

问题1: 查询生产皮带包含red belts的部门信息
select name, belts
from divisions
where find_in_set('red', belts);结果展示

问题2: 查询生产皮带不包含black belts的部门信息
select name, belts
from divisions
where not find_in_set('black', belts);结果展示

问题3:查找名称为o-1或o-2的部门
-- 使用find_in_set
select name, belts
from divisions
where find_in_set(name, 'o-1,o-2');
-- 使用in运算符
select name, belts
from divisions
where name in ('o-1','o-2');
结果展示

补充扩展知识: column in ('x', 'y', 'z')表达式与find_in_set(column, 'x,y,z')效果相同
当你希望将值与数据库中的值列表进行匹配时,可以使用in运算符; 当你希望将值与数据库中以逗号分隔存储的值列表进行匹配时,可以使用find_in_set函数
到此这篇关于mysql中find_in_set函数的使用及问题的文章就介绍到这了,更多相关mysql find_in_set函数内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论