Sử dụng hàm REPLACE() để thay thế khoảng trắng bằng ký tự mong muốn.
Tạo bảng demo
mysql> create table DemoTable (Subject text); Query OK, 0 rows affected (0.86 sec)
Chèn dữ liệu
mysql> insert into DemoTable values('Introduction to MySQL');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('Java in depth');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable values('Data Structure and Algorithm');
Query OK, 1 row affected (0.16 sec)
Hiển thị dữ liệu gốc
mysql> select * from DemoTable;
Kết quả
+------------------------------+ | Subject | +------------------------------+ | Introduction to MySQL | | Java in depth | | Data Structure and Algorithm | +------------------------------+ 3 rows in set (0.00 sec)
Truy vấn thay thế khoảng trắng bằng gạch dưới '_'
mysql> SELECT *, REPLACE(Subject, ' ', '_') as Subject_Name from DemoTable;
Kết quả
+-------------------------------+------------------------------+ | Subject | Subject_Name | +-------------------------------+------------------------------+ | Introduction to MySQL | Introduction_to_MySQL | | Java in depth | Java_in_depth | | Data Structure and Algorithm | Data_Structure_and_Algorithm | +-------------------------------+------------------------------+ 3 rows in set (0.00 sec)
Giải thích REPLACE(str, from_str, to_str): Thay thế tất cả lần xuất hiện của from_str trong str bằng to_str.
Các biến thể:
- Thay nhiều khoảng trắng liên tiếp:
REPLACE(REPLACE(TRIM(Subject), ' ', ' '), ' ', '_')(lặp REPLACE cho đến khi không còn 2 khoảng trắng). - Dùng
REGEXP_REPLACE(MySQL 8.0+) cho regex:REGEXP_REPLACE(Subject, '\\s+', '_'). - Chỉ thay khoảng trắng đầu/cuối:
TRIM(),LTRIM(),RTRIM().
Ứng dụng: Tạo slug URL, normalize key tìm kiếm, format mã code.