• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

mysql中find_in_set施用

mysql 搞代码 7年前 (2018-06-04) 178次浏览 已收录 0个评论

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


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:mysql中find_in_set施用

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址