如何使用 MySQL TRIM() 删除所有行中的空格并更新表?

mysqlmysqli database更新于 2025/5/20 19:56:17

假设一个表的许多值在表的列中有空格,那么这是浪费空间。我们可以使用 TRIM() 函数删除所有行中的空格,并在单个查询中更新表。按照‘Employee’ 中的示例,所有行中都有空格将展示以下概念 −

示例

mysql> Select * from Employee;
+------+----------------------+----------------------+----------------------+
| Id   | Name                 | Address              | Department           |
+------+----------------------+----------------------+----------------------+
| 100  | Raman                | Delhi                | IT                   |
| 101  | Mohan                | Haryana              | History              |
| 102  | Shyam                | Chandigarh           | ENGLISH              |
| 103  | Sukhjeet Singh       | Patiala              | Computer Engg.       |
| 104  | Bimal Roy            | Calcutta             | Computer Engg.       |                    
+------+----------------------+----------------------+----------------------+
5 rows in set (0.00 sec)

从上面的结果集中我们可以看出,Employee 表的行中有很多空格。可以使用以下查询将其删除并更新 −

mysql> Update Employee SET Id = TRIM(Id), Name = TRIM(Name), Address = TRIM(Address), DEPARTMENT = TRIM(Department);
Query OK, 5 rows affected (0.24 sec)
Rows matched: 5 Changed: 5 Warnings: 0

mysql> Select * from Employee;
+------+----------------+------------+----------------+
| Id   | Name           | Address    | Department     |
+------+----------------+------------+----------------+
| 100  | Raman          | Delhi      | IT             |
| 101  | Mohan          | Haryana    | History        |
| 102  | Shyam          | Chandigarh | ENGLISH        |
| 103  | Sukhjeet Singh | Patiala    | Computer Engg. |
| 104  | Bimal Roy      | Calcutta   | Computer Engg. |
+------+----------------+------------+----------------+
5 rows in set (0.00 sec)

从上面的结果集中我们可以看出,所有空格都已被删除,并且表格已更新。


相关文章


有用资源