Mysql中使用FIND_IN_SET解决IN条件为字符串时只有第一个数据可用的问题

262 阅读2分钟

设计了两张表:

1、按钮业务表:每个按钮记录n个设备 2、设备表:设备的其他信息。

开始查询

select sys_id as sysId,mpnt_id as mpntId,attr_id as attrId,data_item_id as dataItemId,data_item_name as dataItemName
from  web_main_wiring_diagram_mpnt
where sys_id=41040020001 and mpnt_id in (select mpnt_Id from web_main_wiring_diagram_button where button_id=1005)	

发现只查出9条数据。而这个按钮对应了两个设备,理论上是有22条的数据的。

对in里面的子查询拆分单独查询:

select mpnt_Id from web_main_wiring_diagram_button where button_id=1005

发现是有两个设备,可为什么查询出来的值都是第一个设备的值呢?继续把in里面的内容替换成字符串 ("1000070001,1000100001") ,发现结果没变,而换成整形时(1000070001,1000100001),或者分割的字符串时("1000070001","1000100001")就发现了是可以查询出所有的。因此,mysql的in 使用的时候如果遇到是一串字符串的时候,只会查询第一个数据。而如果你想用字符串时,该怎么办呢?这时候就出现了这个字符串函数:find_in_set:

select sys_id as sysId,mpnt_id as mpntId,attr_id as attrId,data_item_id as dataItemId,data_item_name as dataItemName
from  web_main_wiring_diagram_mpnt
where sys_id=41040020001 and  FIND_IN_SET(mpnt_id,(select mpnt_id from web_main_wiring_diagram_button where button_id=1005))

对比

find_in_set有三种用法:

【注:a,b,c代表字符串常量,name代表字段名】

**1、find_in_set('b','a,b,c') **

这个是find_in_set主要用法,find_in_set都有返回值, 如这个的返回值为2 ,查不到返回值为0或者null(其中有一个参数为null的情况下返回null)

**2、find_in_set('b',name) **

查找name字段中包含b的字段但是name值的记录方式必须是'a,b,c' 这个用法跟name like "%'b'%" 类似,不同的是:find_in_set是精确匹配,like是模糊匹配, 比如:name的一个值为'a,ab,c' find_in_set则返回为0,like则能查到

3、find_in_set(name,'a,b,c')

这个用法跟name in ('a','b','c')结果是相同的, 区别是find_in_set是拼接成的一个字符串'a,b,c', in是多个字符串'a','b','c'