我們如何從 MySQL 表中一列的值中提取子字串?


我們可以應用 SUBSTRING()、MID() 或 SUBSTR() 等任何函式來從列的值中提取子字串。在這種情況下,我們必須將列的名稱作為函式的第一個引數,即在字串的位置,我們必須給出列的名稱。以下示例將對此進行演示。

示例

假設我們要從“Student”表的“Name”列中提取子字串,然後可以透過使用不同的函式按如下方式進行:

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)

更新時間: 2020 年 2 月 7 日

761 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.