在 MySQL 中從用斜槓分隔的單詞中的字串中獲取子字串?


為此,你可以使用 SUBSTRING_INDEX()。我們首先建立一個 −

mysql> create table DemoTable1416
   -> (
   -> StudentCode varchar(100)
   -> );
Query OK, 0 rows affected (1.56 sec)

使用 insert 在表中插入一些記錄 −

mysql> insert into DemoTable1416 values('101/John/Smith');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1416 values('901/Carol/Taylor');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1416 values('400/David/Miller');
Query OK, 1 row affected (0.12 sec)

使用 select 從表中顯示所有記錄 −

mysql> select * from DemoTable1416;

這將產生以下輸內容 −

+------------------+
| StudentCode      |
+------------------+
| 101/John/Smith   |
| 901/Carol/Taylor |
| 400/David/Miller |
+------------------+
3 rows in set (0.00 sec)

以下是查詢從用斜槓分隔的單詞中的字串中獲取子字串 −

mysql> select substring_index(StudentCode,'/',-2) from DemoTable1416;

這將產生以下輸內容 −

+-------------------------------------+
| substring_index(StudentCode,'/',-2) |
+-------------------------------------+
| John/Smith                          |
| Carol/Taylor                        |
| David/Miller                        |
+-------------------------------------+
3 rows in set (0.00 sec)

更新於: 12-Nov-2019

145 瀏覽量

開啟你的 職業生涯

完成課程取得認證

開始
廣告
© . All rights reserved.