mysql查找字符串函数的使用

来自:网络
时间:2022-12-27
阅读:
目录

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常用十种字符串函数

1.CONCAT()

CONCAT(str1,str2,…))函数用于返回多个字符串连接之后的字符串,例如:

SELECT CONCAT('MySQL', '字符串', '函数') AS str;str      

   

输出

MySQL字符串函数

如果该函数中的任何参数为 NULL,返回结果为 NULL。例如:

SELECT CONCAT('MySQL', NULL, '函数') AS str;
str
|---+   |

对于字符串常量,我们也可直接将它们连写在一起。例如:

SELECT 'MySQL' '字符串' '函数' AS str;
str           
|--------------+MySQL字符串函数|

以上方式只能用于连接字符串常量,不能用于连接字段的值。

返回顶部
顶部