语法解释
FIND_IN_SET(str,strlist)
str是要查询的字符串或者字段;
strlist可以是字段和字符列表,多个字符串之间必须以逗号分隔,例如:'1,2,e,t'。
这个函数的作用就是查询strlist中是否包含str,返回结果为null或记录。假如字符串str在由N个子链组成的字符串列表strlist 中,则返回值的范围在 1 到 N 之间;如果str不在strlist 或strlist 为空字符串,则返回值为 0。例如:
mysql> select find_in_set('s','2,3,s,f,NULL');
+---------------------------------+
| find_in_set('s','2,3,s,f,NULL') |
+---------------------------------+
| 3 |
+---------------------------------+
1 row in set (0.00 sec)
mysql> select find_in_set('vv','2,3,s,f,NULL');
+----------------------------------+
| find_in_set('vv','2,3,s,f,NULL') |
+----------------------------------+
| 0 |
+----------------------------------+
1 row in set (0.00 sec)
mysql> select find_in_set('vv',null);
+------------------------+
| find_in_set('vv',null) |
+------------------------+
| NULL |
+------------------------+
find_in_set()和in的区别
比如有这样的需求,想要取出findin表的list字段中含有vnhg字符串的数据行:
mysql> select * from findin;
+----+------+----------------+
| id | name | list |
+----+------+----------------+
| 1 | vnhg | bnmj,ewer,vnhg |
| 2 | mnn | vbnj,dkf,vnhg |
+----+------+----------------+
mysql> select * from findin where 'vnhg' in(list);
Empty set (0.00 sec)
上面的SQL是无法实现这个需求,实际上只有当list字段的值等于'vnhg'时(和in前面的字符串完全匹配),查询才能返回结果。
使用下面的查询就可以实现需求:
mysql> select * from findin where find_in_set('vnhg',list);
+----+------+----------------+
| id | name | list |
+----+------+----------------+
| 1 | vnhg | bnmj,ewer,vnhg |
| 2 | mnn | vbnj,dkf,vnhg |
+----+------+----------------+
find_in_set()和like的区别
主要的区别就是like是广泛的模糊查询;而 find_in_set() 是精确匹配,并且字段值之间用‘,'分开。
以实际的例子来体会:
mysql> select * from findin where find_in_set('vnh',list);
Empty set (0.00 sec)
mysql> select * from findin where list like '%vnh%';
+----+------+----------------+
| id | name | list |
+----+------+----------------+
| 1 | vnhg | bnmj,ewer,vnhg |
| 2 | mnn | vbnj,dkf,vnhg |
+----+------+----------------+