当前位置: 代码网 > it编程>数据库>Mysql > Mysql中FIND_IN_SET函数的使用及问题

Mysql中FIND_IN_SET函数的使用及问题

2024年07月23日 Mysql 我要评论
find_in_set函数用于返回字符串str在字符串列表str_list中的位置,返回一个整数或一个null值语法格式find_in_set(str,str_list)str:需要查询的字符串str

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函数内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com