如何使用 MySQL 查詢來剪下字串的一部分?


為此,請使用 MySQL 中的 substring_index() 函式。首先,我們建立一個表 -

mysql> create table DemoTable
   -> (
   -> StudentId varchar(100)
   -> );
Query OK, 0 rows affected (0.60 sec)

使用 insert 命令在表中插入一些記錄 -

mysql> insert into DemoTable values('STU-1011');
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable values('STU-95968686');
Query OK, 1 row affected (0.17 sec)

使用 select 語句顯示錶中的所有記錄 -

mysql> select *from DemoTable;

這將產生以下輸出 -

+--------------+
| StudentId    |
+--------------+
| STU-1011     |
| STU-95968686 |
+--------------+
2 rows in set (0.00 sec)

以下是在連字元 (-) 之前剪下 MySQL 中字串一部分的查詢 -

mysql> select substring_index(substring(StudentId, instr(StudentId, "-")+1), " ", 1) from DemoTable;

這將產生以下輸出,顯示連字元 (-) 之前的字串部分

+------------------------------------------------------------------------+
| substring_index(substring(StudentId, instr(StudentId, "-")+1), " ", 1) |
+------------------------------------------------------------------------+
| 1011                                                                   |
| 95968686                                                               |
+------------------------------------------------------------------------+
2 rows in set (0.02 sec)

更新於:30-7 月 -2019

335 次檢視

開啟你的 職業生涯

完成本課程以獲得認證資格

開始
廣告
© . All rights reserved.