mysql if find_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);

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值