在 MySQL 中从以斜线分隔的单词字符串中获取子字符串?
mysqlmysqli database
为此,您可以使用 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)