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)
SELECT CHAR_LENGTH(‘MySQL字符串函数’) AS len1, CHARACTER_LENGTH(‘MySQL字符串函数’) AS len2; len1|len2 |—-+—-+ 10| 10|
BIT_LENGTH(str)函数用于返回字符串的比特长度(比特数量),例如:
SELECT BIT_LENGTH(‘MySQL字符串函数’) AS len; len |—+160|
一个字节包含 8 个比特。
5.SUBSTRING()
SUBSTRING(str,pos)、SUBSTRING(str FROM pos)、SUBSTRING(str,pos,len)以及SUBSTRING(str FROM pos FOR len)函数都可以用于返回从指定位置 pos 开始的子串,len 表示返回子串的长度;pos 为 0 表示返回空字符串。例如:
SELECT SUBSTRING(‘MySQL字符串函数’, 6) AS str1, SUBSTRING(‘MySQL字符串函数’ FROM 6) AS str2, SUBSTRING(‘MySQL字符串函数’, 6, 3) AS str3, SUBSTRING(‘MySQL字符串函数’ FROM 6 FOR 3) AS str4, SUBSTRING(‘MySQL字符串函数’, 0) AS str5;str1 | str2 |str3 |str4 |str5 |———+———+——-+——+—-+字符串函数|字符串函数|字符串 |字符串 | |
位置参数 pos 可以为负数,此时返回的子串从字符串右侧第 pos 个字符开始。例如:
SELECT SUBSTRING(‘MySQL字符串函数’, -2) AS str1, SUBSTRING(‘MySQL字符串函数’, -5, 3) AS str2; str1 |str2 |——+——+函数 |字符串 |
SELECT TRIM(LEADING ‘ ‘ FROM ‘ MySQL字符串函数 ‘) AS str1, TRIM(TRAILING ‘-‘ FROM ‘–MySQL字符串函数–‘) AS str2; str1 |str2 |—————-+—————-+MySQL字符串函数 |–MySQL字符串函数|
发表评论