如何在 MySQL 中通过删除分隔符和分隔符后的数字来更新当前值的子字符串值?

mysqlmysqli database

这里,假设您有一个字符串,其形式为"StringSeparatorNumber",例如 John/56989。现在,如果您想删除分隔符 / 后的数字,请使用 SUBSTRING_INDEX()。让我们首先创建一个表 −

mysql> create table DemoTable
(
   StudentName varchar(100)
);
Query OK, 0 rows affected (1.05 sec)

使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable values('John/56989');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Carol');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable values('David/74674');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values('Bob/45565');
Query OK, 1 row affected (0.09 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable;

这将产生以下输出 −

+-------------+
| StudentName |
+-------------+
| John/56989  |
| Carol       |
| David/74674 |
| Bob/45565   |
+-------------+
4 rows in set (0.00 sec)

以下是使用当前值的子字符串更新值的查询 −

mysql> update DemoTable set StudentName=substring_index(StudentName,'/',1);
Query OK, 3 rows affected (0.13 sec)
Rows matched :4 Changed :3 Warnings :0

让我们再次检查表记录 −

mysql> select *from DemoTable;

这将产生以下输出 −

+-------------+
| StudentName |
+-------------+
| John        |
| Carol       |
| David       |
| Bob         |
+-------------+
4 rows in set (0.00 sec)

相关文章