如何從 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