如何從 MySQL 中的一個列中去除所有空格?


要從 MySQL 中的一列中去除所有空格,可以使用 REPLACE() 函式。以下為語法 −

update yourTableName set yourColumnName=REPLACE(yourColumnName,' ', '' );

我們先建立一個表 −

mysql> create table stripAllSpacesDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.56 sec)

以下為使用 insert 命令在表中插入記錄的查詢 −

mysql> insert into stripAllSpacesDemo(Name) values('Jo h n');
Query OK, 1 row affected (0.19 sec)
mysql> insert into stripAllSpacesDemo(Name) values(' Joh n');
Query OK, 1 row affected (0.16 sec)
mysql> insert into stripAllSpacesDemo(Name) values('Jo hn');
Query OK, 1 row affected (0.14 sec)
mysql> insert into stripAllSpacesDemo(Name) values('J ohn');
Query OK, 1 row affected (0.17 sec)
mysql> insert into stripAllSpacesDemo(Name) values('John ');
Query OK, 1 row affected (0.14 sec)

以下為使用 select 語句從表中顯示所有記錄的查詢 −

mysql> select * from stripAllSpacesDemo;

這將產生以下輸出 −

+----+-----------+
| Id | Name      |
+----+-----------+
| 1  | Jo h n    |
| 2  | Joh n     |
| 3  | Jo hn     |
| 4  | J ohn     |
| 5  | John      |
+----+-----------+
5 rows in set (0.00 sec)

以下是從 MySQL 中的一列中去除所有空格的查詢 −

mysql> update stripAllSpacesDemo set Name=REPLACE(Name,' ','');
Query OK, 5 rows affected (0.12 sec)
Rows matched: 5 Changed: 5 Warnings: 0

再次顯示錶中的所有記錄,以檢查是否所有空格都已去除 −

mysql> select * from stripAllSpacesDemo;

這將產生以下輸出 −

+----+------+
| Id | Name |
+----+------+
| 1  | John |
| 2  | John |
| 3  | John |
| 4  | John |
| 5  | John |
+----+------+
5 rows in set (0.00 sec)

更新時間: 30-Jul-2019

1K+ 瀏覽量

激發你的職業生涯

完成課程即可獲得證書

開始學習
廣告
© . All rights reserved.