MySQL函数find_in_set()

2023-12-14  本文已影响0人  AC编程

一、官方涵义

find_in_set(str,strlist): str 要查询的字符串,strlist 需查询的字段,参数以”,”分隔,形式如 (1,2,6,8,10,22);该函数的作用是查询字段(strlist)中是否包含(str)的结果,返回结果为null或记录。

select find_in_set('b', 'a,b,c,d');
// 结果:2
// 因为 b 在strlist集合中2的位置, a是位置1
 
select find_in_set('1', '1');
// 结果:1 
// 这时候的strlist集合有点特殊,只有一个字符串
 
select find_in_set('2', '1,2'); 
// 结果:2
 
select find_in_set('6', '1'); 
// 结果:0 strlist中不存在str,所以返回0。

综上: find_in_set函数中,若前一个字符串包含在后一个字符串集合中,返回大于0的数,该数为前一个字符串在后一个字符串中的位置。

二、find_in_set() 和 in 的区别

三、应用场景

3.1 文章表type字段查询

文章表里面有个type字段,它存储的是文章类型,有 1头条、2推荐、3热点、4图文等等 。现在有篇文章他既是头条,又是热点,还是图文,type中以 1,3,4 的格式存储。那我们如何用sql查找所有type中有4的图文类型的文章呢?

select * from article where find_in_set('4',type)
3.2 部门树查询,匹配当前节点及所有子节点

数据表字段说明:

部门

匹配部门id或父id为100的数据:

select dept_id from sys_dept where dept_id = 100 or find_in_set( 100 , ancestors ) 

转载自:MYSQL中 find_in_set() 函数用法详解

上一篇 下一篇

猜你喜欢

热点阅读