mysql中find_in_set施用

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 |

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

mysql中find_in_set施用

相关文章:

你感兴趣的文章:

标签云: