如何使用 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.