Mysql函数FIND_IN_SET 字符串列表是由以字符分隔的子字符串组成的字符串的查询

86 阅读1分钟

官方文档

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

    翻译

    如果字符串*n* 在由子字符串组成的 *strlist*字符串列表中 ,则 返回 1 到范围内的值 。

    字符串列表是由以字符分隔的子字符串组成的字符串 。

    如果第一个参数是常量字符串,第二个参数是 type 的列 ,则 函数被优化为使用位算术。

    如果str不在strlist 或strlist 为空字符串,则返回值为 0 。如任意一个参数为NULL,则返回值为 NULL。这个函数在第一个参数包含一个逗号(‘,')时将无法正常运行。

    //返回的是b所在位置2
    mysql> SELECT FIND_IN_SET('b','a,b,c,d');
            -> 2
            
    //返回的是z所在位置,没有z,所以返回0
    mysql> SELECT FIND_IN_SET('z','a,b,c,d');
            -> 0
    

当字段值是以字符分隔的字符串时,需要用FIND_IN_SET查询

表结构(区县名称是一个用逗号分隔的字符串)符合函数使用要求

image.png

image.png

//查询包含 `蜀山区` 的对象
SELECT *
FROM XXX where
FIND_IN_SET('蜀山区', district_name)

FIND_IN_SET和LIKE区别

  • LIKE是模糊查询
  • FIND_IN_SET是精确查询

欢迎留言讨论补充