您的位置:首页 > 数据库 > MySQL

mysql find_in_set 用法

2015-06-09 17:10 645 查看
昨天在处理一需求时,需要从数据库字段中查出包含了某字符串的数据,第一反应就是能不能用mysql in关键字(MySQL IN 用法),但是最终查询的结果不是自己想要的。最终在谷歌上搜索到可以使用mysql find_in_set 函数来处理,下面介绍一下 find_in_set 的使用方法:

首先,看一下数据库表数据:

复制代码 代码如下:
mysql> select * from test;

+----+-------------+

| id | name |

+----+-------------+

| 1 | name1,nam2 |

| 2 | name1 |

| 3 | name3 |

| 4 | name2,name4 |

| 5 | name3,name5 |

+----+-------------+

5 rows in set (0.00 sec)

现在我们就需要从这些数据中查询出 name 字段中包含有name1的数据。
我们先使用 in 来查询一下:

复制代码 代码如下:
mysql> select * from test where name in ('name1');

+----+-------+

| id | name |

+----+-------+

| 2 | name1 |

+----+-------+

1 row in set (0.00 sec)

可以看到只查询出了一条数据,显然不是我们想要的结果。
使用 find_in_set:

复制代码 代码如下:
mysql> select * from test where find_in_set('name1',name);

+----+------------+

| id | name |

+----+------------+

| 1 | name1,nam2 |

| 2 | name1 |

+----+------------+

2 rows in set (0.02 sec)

结果是正确的,是我们想要的。
下面解释下find_in_set 函数:

find_in_set(str1,str2) 函数:返回str2中str1所在的位置索引,其中str2必须以","分割开。
参考mysql文档中的解释:http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_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

其中有点需要再次提醒的是:strlist必须以逗号(,)分隔。
我们可以来做个试验,把test表中name字段的链接字符“,”改为"-"。

复制代码 代码如下:
mysql> select * from test;

+----+-------------+

| id | name |

+----+-------------+

| 1 | name1-nam2 |

| 2 | name1 |

| 3 | name3 |

| 4 | name2-name4 |

| 5 | name3-name5 |

+----+-------------+

5 rows in set (0.00 sec)

再次使用find_in_set查询name字段中包含有name1的数据。

复制代码 代码如下:
mysql> select * from test where find_in_set('name1',name);

+----+-------+

| id | name |

+----+-------+

| 2 | name1 |

+----+-------+

1 row in set (0.00 sec)

可以看到结果只有一条了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: