MYSQL关于FIND_IN_SET函数的使用

FIND_IN_SET(str,strlist)

Returns a value in the range of 1 to N  if the string str is in the string list strlist consisting of N substrings. A string list is a string composed of substrings separated by , characters. If the first argument is a constant string and the second is a column of type SET, the FIND_IN_SET() function is optimized to use bit arithmetic. Returns 0 if str is not in strlist or if strlist is the empty string. Returns NULL if either argument is NULL. This function does not work properly if the first argument contains a comma (,) character.

按照上文的意思FIND_IN_SET()函数是当str存在于集合1...N中时,就会将1...N返回,strlist表示由N个子字符串组成的集合,这些子字符串用“,”来分隔。如果str不存在于strlist中或strlist为空时则返回0,当两个参数都不指定值得时候则返回NULL,如果第一个参数是逗号该函数不能使用

mysql> SELECT FIND_IN_SET('b','a,b,c,d');


        -> 2

在网上看到这个函数被用于按照给定的传值顺序来返回结果的顺序(有时候我们需要按照传值的顺序排序而不是让mysql默认排序结果集)

如给定下面一张表
+----+-------+
| id | name  |
+----+-------+
|  1 | test1 |
|  2 | test2 |
|  3 | test3 |
|  4 | test4 |
|  5 | test5 |
+----+-------+
常规显示如下
select * from test where id in(3,1,5);
+----+-------+
| id | name  |
+----+-------+
|  1 | test1 |
|  3 | test3 |
|  5 | test5 |
+----+-------+
通过以下方式保证显示顺序为3->1->5
select * from test where id in(3,1,5) order by find_in_set(id,'3,1,5');
另外提到的方法:
select * from test where id in(3,1,5) order by substring_index('3,1,2',id,1);

以上方法都是不考虑语句效率的。

你可能感兴趣的:(mysql,find_in_set)