在 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.