在 MySQL 中去除列的最后两个字符?
mysqlmysqli database
您可以借助 SUBSTRING() 和 CHAR_LENGTH() 方法去除最后两个字符。语法如下 −
select yourColumnName,SUBSTRING(yourColumnName,1,CHAR_LENGTH(yourColumnName) - 2) AS anyVariableName from yourTableName;
为了理解上述语法,让我们创建一个表 −
mysql> create table LastTwoCharacters −> ( −> Words varchar(200) −> ); Query OK, 0 rows affected (0.71 sec)
现在您可以借助 select 语句在表中插入一些记录。插入记录的查询如下−
mysql> insert into LastTwoCharacters values('Hellooo'); Query OK, 1 row affected (0.23 sec) mysql> insert into LastTwoCharacters values('Worldsss'); Query OK, 1 row affected (0.10 sec) mysql> insert into LastTwoCharacters values('Johnson'); Query OK, 1 row affected (0.22 sec)
使用 select 语句显示所有记录 −
mysql> select *from LastTwoCharacters;
以下是输出 −
+----------+ | Words | +----------+ | Hellooo | | Worldsss | | Johnson | +----------+ 3 rows in set (0.00 sec)
以下是删除列的最后两个字符的查询 −
mysql> select Words,SUBSTRING(Words,1,CHAR_LENGTH(Words) - 2) AS AfterStripLastTwoChar from LastTwoCharacters;
以下是输出 −
+----------+-----------------------+ | Words | AfterStripLastTwoChar | +----------+-----------------------+ | Hellooo | Hello | | Worldsss | Worlds | | Johnson | Johns | +----------+-----------------------+ 3 rows in set (0.00 sec)