如何使用 MySQL 查询截取字符串的一部分?
mysqlmysqli database
为此,请使用 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)