天天看點

mysql中find_in_set使用

mysql中find_in_set使用

手冊上是這樣解釋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.

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

               ->; 2

我們在實際中使用這個函數則是由于排序的需要。

例如,有個game表,其中包括字段gameid和title,現在需要根據一個gameid的集合來獲得game表中對應的title字段,可以使用

mysql>; select gameid,title from game where gameid in(3,1,2);

來獲得這樣的結果:

+——–+——————–+

| gameid | title |

+——–+——————–+

| 1 | Young Lee |

| 2 | Dark Matter |

| 3 | Armed With Wings 2 |

+——–+——————–+

我們會發現,傳回結果并不是按照我們給定的gameid集合的順序來排序的。

如果需要傳回結果按(3,1,2)來排序的話,就需要使用find_in_set了。

mysql>; select gameid,title from game where gameid in(3,1,2) order by find_in_set

(gameid,'3,1,2');

傳回的結果如下:

+——–+——————–+

| gameid | title |

+——–+——————–+

| 3 | Armed With Wings 2 |

| 1 | Young Lee |

| 2 | Dark Matter |

+——–+——————–+