如何使用 MySQL 修剪逗号?

mysqlmysqli database

修剪逗号的语法如下 −

SELECT TRIM(BOTH ',' FROM yourColumnName) from yourTableName;

让我们看一个例子 −

mysql> create table TrimCommasDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> AllTechnicalSkills text
   -> );
Query OK, 0 rows affected (0.81 sec)

现在,您可以使用 insert 命令在表中插入一些记录。查询如下 −

mysql> insert into TrimCommasDemo(AllTechnicalSkills) values(',C,C++,Java,');
Query OK, 1 row affected (0.14 sec)
mysql> insert into TrimCommasDemo(AllTechnicalSkills) values(',MySQL,SQL
Server,MongoDB,');
Query OK, 1 row affected (0.13 sec)
mysql> insert into TrimCommasDemo(AllTechnicalSkills) values(',Spring
Framework,Hibernate Framework,');
Query OK, 1 row affected (0.13 sec)

使用 select 语句显示表中的所有记录。查询如下 −

mysql> select *from TrimCommasDemo;

这是输出 −

+----+----------------------------------------+
| Id | AllTechnicalSkills                     |
+----+----------------------------------------+
| 1  | ,C,C++,Java,                           |
| 2  | ,MySQL,SQL Server,MongoDB,             |
| 3  | ,Spring Framework,Hibernate Framework, |
+----+----------------------------------------+
3 rows in set (0.00 sec)

以下是使用 MySQL 修剪前导和尾随逗号的查询 −

mysql> select TRIM(BOTH ',' FROM AllTechnicalSkills) from TrimCommasDemo;

这是输出 −

+----------------------------------------+
| TRIM(BOTH ',' FROM AllTechnicalSkills) |
+----------------------------------------+
| C,C++,Java                             |
| MySQL,SQL Server,MongoDB               |
| Spring Framework,Hibernate Framework   |
+----------------------------------------+
3 rows in set (0.00 sec)

相关文章