使用MYSQL查询数据表中某个字段包含某个数值(find_in_set()函数)

场景介绍

人有时会身兼数职,需要查找出其中担任某一职务的都有哪些人,如下面position字段,不同的职务用数字表示,多个职务以逗号隔开。

先要查找出担任1职务的人员,通过以下两种方式来查询。

方式一

采用模糊查询,匹配出1职务的记录,如下SQL:

select * from user where position like '%1%'
  • 1

查询结果如下,仔细观察你会发现position为10的也被查出来了,但这个不符合业务要求。

方式二

采用MySQL的原生函数find_in_set(str,array)来查询,SQL如下:

select * from user where find_in_set(1,position)
  •  

查询结果如下,符合要求。

函数介绍

FIND_IN_SET(str,strlist),注意其中strlist只识别英文逗号。

参考资料:(场景数据用法比较全)

https://blog.csdn.net/qq_25112523/article/details/97135604?utm_medium=distribute.pc_relevant_t0.none-task-blog-OPENSEARCH-1.channel_param&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-OPENSEARCH-1.channel_param

おすすめ

転載: blog.csdn.net/zty1317313805/article/details/108399754