MySQL 如何从MySQL表中的列值中提取子字符串?

MySQL 如何从MySQL表中的列值中提取子字符串?

我们可以应用任何一个函数,如SUBSTRING()、MID()或SUBSTR()来从列的值中提取子字符串。在这种情况下,我们必须把列的名称作为函数的第一个参数,即在字符串的位置上给出列的名称,以下例子将说明它。

阅读更多:MySQL 教程

示例

假设我们要从“学生”表的“名字”列中提取子字符串,则可以使用不同的函数来实现,如下所示 −

mysql> Select name, SUBSTR(name,2,4) from student;
+---------+------------------+
| name    | SUBSTR(name,2,4) |
+---------+------------------+
| Gaurav  | aura             |
| Aarav   | arav             |
| Harshit | arsh             |
| Gaurav  | aura             |
| Yashraj | ashr             |
+---------+------------------+
5 rows in set (0.00 sec)

mysql> Select name, MID(name,2,4) from student;
+---------+---------------+
| name    | MID(name,2,4) |
+---------+---------------+
| Gaurav  | aura          |
| Aarav   | arav          |
| Harshit | arsh          |
| Gaurav  | aura          |
| Yashraj | ashr          |
+---------+---------------+
5 rows in set (0.00 sec)

mysql> Select name, substring(name,2,4) from student;
+---------+---------------------+
| name    | substring(name,2,4) |
+---------+---------------------+
| Gaurav  | aura                |
| Aarav   | arav                |
| Harshit | arsh                |
| Gaurav  | aura                |
| Yashraj | ashr                |
+---------+---------------------+
5 rows in set (0.00 sec)

我们还可以在以上查询中应用条件,如下所示 −

mysql> Select name, substring(name,2,4) from student WHERE address = 'delhi';
+---------+---------------------+
| name    | substring(name,2,4) |
+---------+---------------------+
| Gaurav  | aura                |
| Harshit | arsh                |
+---------+---------------------+
2 rows in set (0.16 sec)

mysql> Select name, MID(name,2,4) from student WHERE address = 'delhi';
+---------+---------------+
| name    | MID(name,2,4) |
+---------+---------------+
| Gaurav  | aura          |
| Harshit | arsh          |
+---------+---------------+
2 rows in set (0.00 sec)

mysql> Select name, SUBSTR(name,2,4) from student WHERE address = 'delhi';
+---------+------------------+
| name    | SUBSTR(name,2,4) |
+---------+------------------+
| Gaurav  | aura             |
| Harshit | arsh             |
+---------+------------------+
2 rows in set (0.00 sec)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程