如何从 MySQL 的所有字段中删除前两个字符?
若要删除所有字段的前两个字符,需要使用 MySQL 中的 SUBSTRING() 函数。语法如下所示 −
UPDATE yourTableName SET yourColumnName=SUBSTRING(yourColumnName,3) WHERE yourCondition;
为了理解上述语法,我们创建一个表。创建表的查询如下 −
mysql> create table RemoveFirstTwoCharacterDemo -> ( -> Id int NOT NULL AUTO_INCREMENT, -> StringValue varchar(30), -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (1.04 sec)
使用 insert 命令向表中插入一些记录。查询如下 −
mysql> insert into RemoveFirstTwoCharacterDemo(StringValue) values('U:100'); Query OK, 1 row affected (0.13 sec) mysql> insert into RemoveFirstTwoCharacterDemo(StringValue) values('S:20'); Query OK, 1 row affected (0.21 sec) mysql> insert into RemoveFirstTwoCharacterDemo(StringValue) values('N/A'); Query OK, 1 row affected (0.12 sec) mysql> insert into RemoveFirstTwoCharacterDemo(StringValue) values('T:8'); Query OK, 1 row affected (0.16 sec) mysql> insert into RemoveFirstTwoCharacterDemo(StringValue) values('N/A'); Query OK, 1 row affected (0.12 sec) mysql> insert into RemoveFirstTwoCharacterDemo(StringValue) values('W:99'); Query OK, 1 row affected (0.19 sec)
使用 select 语句显示表中的所有记录。查询如下 −
mysql> select *from RemoveFirstTwoCharacterDemo;
输出如下 −
+----+-------------+ | Id | StringValue | +----+-------------+ | 1 | U:100 | | 2 | S:20 | | 3 | N/A | | 4 | T:8 | | 5 | N/A | | 6 | W:99 | +----+-------------+ 6 rows in set (0.00 sec)
以下是删除前两个字符的查询 −
mysql> update RemoveFirstTwoCharacterDemo set StringValue=SUBSTRING(StringValue,3) -> where StringValue <> 'N/A'; Query OK, 4 rows affected (0.27 sec) Rows matched: 4 Changed: 4 Warnings: 0
再次使用 select 语句检查表记录。查询如下 −
mysql> select *from RemoveFirstTwoCharacterDemo;
输出如下 −
+----+-------------+ | Id | StringValue | +----+-------------+ | 1 | 100 | | 2 | 20 | | 3 | N/A | | 4 | 8 | | 5 | N/A | | 6 | 99 | +----+-------------+ 6 rows in set (0.00 sec)
广告