Để gộp nhiều cột/tham số thành một chuỗi và lưu vào một cột đơn (ví dụ: cột thông tin tóm tắt), dùng CONCAT_WS(separator, col1, col2, ...) trong câu lệnh INSERT.
Ví dụ minh họa
Tạo bảng:
mysql> create table DemoTable (
Name varchar(100),
Age int,
CountryName varchar(100),
PersonInformation text
);
INSERT với CONCAT_WS gộp 3 cột thành 1:
mysql> insert into DemoTable values('John',21,'US',concat_ws('-',Name,Age,CountryName));
mysql> insert into DemoTable values('Chris',22,'AUS',concat_ws('-',Name,Age,CountryName));
mysql> insert into DemoTable values('Bob',24,'UK',concat_ws('-',Name,Age,CountryName));
Hiển thị kết quả:
mysql> select * from DemoTable;
Kết quả:
+-------+------+-------------+-------------------+ | Name | Age | CountryName | PersonInformation | +-------+------+-------------+-------------------+ | John | 21 | US | John-21-US | | Chris | 22 | AUS | Chris-22-AUS | | Bob | 24 | UK | Bob-24-UK | +-------+------+-------------+-------------------+
Giải thích:
CONCAT_WS('-', Name, Age, CountryName): WS = With Separator. Nối các đối số với phân cách '-'- Ưu điểm so với CONCAT(): Tự động bỏ qua NULL (không tạo '--' nếu có NULL)
- Tham chiếu cột Name, Age, CountryName trong cùng câu INSERT được MySQL hỗ trợ
Ứng dụng: Tạo cột search index, full-text search, log audit, cache hiển thị, QR code data, v.v.
Lưu ý: Nếu cần cập nhật sau khi dữ liệu thay đổi, dùng UPDATE ... SET PersonInformation = CONCAT_WS('-', Name, Age, CountryName) hoặc trigger ON UPDATE.