如何使用 SUBSTRING_INDEX() 在 MySQL 中拆分字串?


我們首先建立一個表 −

mysql> create table DemoTable1465
   -> (
   -> Name varchar(40)
   -> );
Query OK, 0 rows affected (0.54 sec)

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

mysql> insert into DemoTable1465 values('Chris Brown');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1465 values('David Miller');
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable1465 values('John Doe');
Query OK, 1 row affected (0.14 sec)

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

mysql> select * from DemoTable1465;

這將生成以下輸出 −

+--------------+
| Name         |
+--------------+
| Chris Brown  |
| David Miller |
| John Doe     |
+--------------+
3 rows in set (0.00 sec)

以下是使用 SUBSTRING_INDEX() 在 MySQL 中拆分字串的查詢。在這裡,我們拆分名字和姓氏字串 −

mysql> select
   -> substring_index(substring_index(Name, ' ', 1), ' ', -1) as StudentFirstName,
   ->   substring_index(substring_index(Name, ' ', 3), ' ', -1) AS StudentLastName
   -> from DemoTable1465;

這將生成以下輸出 −

+------------------+-----------------+
| StudentFirstName | StudentLastName |
+------------------+-----------------+
| Chris            |           Brown |
| David            |          Miller |
| John             |             Doe |
+------------------+-----------------+
3 rows in set (0.00 sec)

更新於: 2019 年 12 月 10 日

192 次瀏覽

開啟你的 職業生涯

透過完成本課程獲得認證

開始
廣告
© . All rights reserved.