如何从 MySQL 表中的列中提取子字符串?
我们可以应用 SUBSTRING()、MID() 或 SUBSTR() 等任何函数,从列的值中提取子字符串。在这种情况下,我们必须将列的名称作为函数的第一个参数,即将要提供列名的字符串位置。以下示例对其进行了说明。
示例
假设我们要从“学生”表中的“姓名”列提取子字符串,则可以使用不同的函数进行操作,如下所示:-
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)
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP