如何使用 MySQL 中的子字符串更新当前值的值,去除分隔符和分隔符后面的数字?
在这里,假设您有一个形式为“ 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)
阅读更多:MySQL 教程
极客教程