MYSQL關於FIND_IN_SET函數的使用

FIND_IN_SET(str,strlist) mysql

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.sql

按照上文的意思FIND_IN_SET()函數是當str存在於集合1...N中時,就會將1...N返回,strlist表示由N個子字符串組成的集合,這些子字符串用「,」來分隔。若是str不存在於strlist中或strlist爲空時則返回0,當兩個參數都不指定值得時候則返回NULL,若是第一個參數是逗號該函數不能使用bash

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


        -> 2

在網上看到這個函數被用於按照給定的傳值順序來返回結果的順序(有時候咱們須要按照傳值的順序排序而不是讓mysql默認排序結果集)ide

如給定下面一張表
+----+-------+
| 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);

以上方法都是不考慮語句效率的。函數

相關文章
相關標籤/搜索