删除 MySQL 列中用括号括起来的尾部数字


为此,请结合使用 trim() 与 substring()。我们先创建一个表 −

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

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

mysql> insert into DemoTable values('1stJohn');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('1stJohn (7)');
Query OK, 1 row affected (0.65 sec)
mysql> insert into DemoTable values('2ndSam');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('2ndSam (4)');
Query OK, 1 row affected (0.15 sec)

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

mysql> select *from DemoTable;

将会产生以下输出 −

+-------------+
| Name        |
+-------------+
| 1stJohn     |
| 1stJohn (7) |
| 2ndSam      |
| 2ndSam (4)  |
+-------------+
4 rows in set (0.00 sec)

以下是查询以从 MySQL 列中删除用括号括起来的尾部数字 −

mysql> select trim(substring(Name, 1, (CHAR_LENGTH(Name) - LOCATE('(', REVERSE(Name))))) AS RemovingTrailingNumbers from DemoTable;

将会产生以下输出 −

+-------------------------+
| RemovingTrailingNumbers |
+-------------------------+
| 1stJohn                 |
| 1stJohn                 |
| 2ndSam                  |
| 2ndSam                  |
+-------------------------+
4 rows in set (0.00 sec)

更新时间:26-9 月 -2019

140 次浏览

开启您的 职业

完成课程认证

入门
广告
© . All rights reserved.