MySQL查询删除字符串中最后一个逗号后的所有字符?
要删除字符串中最后一个逗号之后的所有字符,可以使用SUBSTRING_INDEX()。
如果您不知道最后一个逗号的位置,则需要使用来动态查找最后一个逗号LENGTH()
。
语法如下-
UPDATE yourTableName set yourColumnName = SUBSTRING_INDEX(yourColumnName, ',', LENGTH(yourColumnName) - LENGTH(REPLACE(yourColumnName, ',', '')));
为了理解上述语法,让我们创建一个表。创建表的查询如下-
mysql> create table RemoveAllCharacters -> ( -> Id int NOT NULL AUTO_INCREMENT, -> FullInfo varchar(200), -> PRIMARY KEY(Id) -> );
使用insert命令在表中插入一些记录。查询如下-
mysql> insert into RemoveAllCharacters(FullInfo) values('John,Smith,23,98,4565886'); mysql> insert into RemoveAllCharacters(FullInfo) values('Carol,Taylor,26,91'); mysql> insert into RemoveAllCharacters(FullInfo) values('David,Miller,21'); mysql> insert into RemoveAllCharacters(FullInfo) values('Robert,Jones,22,97'); mysql> insert into RemoveAllCharacters(FullInfo) values('Sam,Williams,27,88,456788,97877');
使用select语句显示表中的所有记录。查询如下-
mysql> select *from RemoveAllCharacters;
以下是输出-
+----+---------------------------------+ | Id | FullInfo | +----+---------------------------------+ | 1 | John,Smith,23,98,4565886 | | 2 | Carol,Taylor,26,91 | | 3 | David,Miller,21 | | 4 | Robert,Jones,22,97 | | 5 | Sam,Williams,27,88,456788,97877 | +----+---------------------------------+ 5 rows in set (0.00 sec)
以下是删除字符串中最后一个逗号后的所有字符的查询-
mysql> update RemoveAllCharacters -> set FullInfo = SUBSTRING_INDEX(FullInfo, ',', LENGTH(FullInfo) - LENGTH(REPLACE(FullInfo, ',', ''))); Rows matched: 5 Changed: 5 Warnings: 0
现在再次检查表的所有记录。查询如下-
mysql> select *from RemoveAllCharacters;
以下是显示最后一个逗号后没有字符的记录的输出:
+----+---------------------------+ | Id | FullInfo | +----+---------------------------+ | 1 | John,Smith,23,98 | | 2 | Carol,Taylor,26 | | 3 | David,Miller | | 4 | Robert,Jones,22 | | 5 | Sam,Williams,27,88,456788 | +----+---------------------------+ 5 rows in set (0.00 sec)