Find in set() function of MySQL

Grammatical explanation

FIND_IN_SET(str,strlist)

str is the string or field to query;
strlist can be a list of fields and characters, multiple strings must be separated by commas, for example: '1,2,e,t'.

The function is to query whether str is included in strlist, and return null or record. If the string str is in the string list strlist composed of N sub chains, the return value range is between 1 and N; if str is not in strlist or strlist is an empty string, the return value is 0. For example:

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 |
+------------------------+

The difference between find in set() and in

For example, if you want to retrieve the data row with vnhg string in the list field of the findin table:

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)

The above SQL cannot fulfill this requirement. In fact, only when the value of the list field is equal to 'vnhg' (exactly matching the string before in), can the query return the result.
Use the following query to implement the requirements:

mysql> select * from findin where find_in_set('vnhg',list);
+----+------+----------------+
| id | name | list           |
+----+------+----------------+
|  1 | vnhg | bnmj,ewer,vnhg |
|  2 | mnn  | vbnj,dkf,vnhg  |
+----+------+----------------+

The difference between find in set() and like

The main difference is that like is an extensive fuzzy query, while find_in_set() is an exact match, and the field values are separated by ','.
Experience with practical examples:

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  |
+----+------+----------------+

Keywords: Database MySQL SQL

Added by thom2002 on Mon, 30 Dec 2019 20:27:18 +0200