去除 MySQL 中某列最后的两个字符?
借助于 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)
广告