mysql查找字符串的函数_mysql查找字符串函数

一、根据字符串找位置

find_in_set

第二个参数是以逗号隔开的,从第二个参数集合中查找第一个参数的位置

mysql> select find_in_set('mysql','oracle,sql server,mysql,db2');

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

| find_in_set('mysql','oracle,sql server,mysql,db2') |

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

| 3 |

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

1 row in set (0.00 sec)

field

mysql> help field

Name: 'FIELD'

Description:

Syntax:

FIELD(str,str1,str2,str3,...)

Returns the index (position) of str in the str1, str2, str3, ... list.

Returns 0 if str is not found.

If all arguments to FIELD() are strings, all arguments are compared as

strings. If all arguments are numbers, they are compared as numbers.

Otherwise, the arguments are compared as double.

If str is NULL, the return value is 0 because NULL fails equality

comparison with any value. FIELD() is the complement of ELT().

URL: http://dev.mysql.com/doc/refman/5.5/en/string-functions.html

Examples:

mysql> SELECT FIELD('ej', 'Hej', 'ej', 'Heja', 'hej', 'foo');

-> 2

mysql> SELECT FIELD('fo', 'Hej', 'ej', 'Heja', 'hej', 'foo');

-> 0

上面两个函数都是全匹配,如下三个函数是子字符串匹配。

locate(str1,str)

position(str1 in str)

instr(str,str1)

这三个函数都是返回参数str中字符串str1的开始位置,注意locate和instr参数的顺序

mysql> select locate('sql','mysql') locate ,position('sql' in 'mysql') position ,instr('mysql','sql') instr;

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

| locate | position | instr |

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

| 3 | 3 | 3 |

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

1 row in set (0.00 sec)

二、根据位置找字符串

elt(n,str1,str2,…)

elt函数返回指定位置的字符串,项目上如果有这个需求的话,直接使用这个函数还是挺便利的。

mysql> select elt(2,'huang','bao','kang');

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

| elt(2,'huang','bao','kang') |

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

| bao |

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

1 row in set (0.00 sec)

make_set

相对于elt函数,elt函数只能选择一个具体位置的元素,而make_set则更强大,将换算二进制之后为条件进行选择。1为选择,0不选择。

mysql> select bin(5),make_set(5,'huang','bao','kang','Love you!');

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

| bin(5) | make_set(5,'huang','bao','kang','Love you!') |

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

| 101 | huang,kang |

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

1 row in set (0.00 sec)

你可能感兴趣的:(mysql查找字符串的函数)