Giới thiệu
Sử dụng GROUP_CONCAT() để gộp nhiều hàng cùng nhóm thành một chuỗi, phân cách bởi dấu phẩy (hoặc tùy chỉnh).
1. Tạo bảng và dữ liệu
mysql> create table DemoTable1561 (
-> StudentName varchar(20),
-> Title text
-> );
Query OK, 0 rows affected (0.60 sec)
mysql> insert into DemoTable1561 values('Adam','Learning Java');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1561 values('Bob','Learning C');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1561 values('Adam','Learning Spring and Hibernate Framework');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable1561 values('Carol','Learning MySQL from basic');
Query OK, 1 row affected (0.30 sec)
2. Dữ liệu gốc
mysql> select * from DemoTable1561;
+-------------+-----------------------------------------+ | StudentName | Title | +-------------+-----------------------------------------+ | Adam | Learning Java | | Bob | Learning C | | Adam | Learning Spring and Hibernate Framework | | Carol | Learning MySQL from basic | +-------------+-----------------------------------------+ 4 rows in set (0.00 sec)
3. Gom nhóm theo tên học sinh
mysql> select StudentName,
-> group_concat(Title separator ',') as FormattedOutput
-> from DemoTable1561
-> group by StudentName;
4. Kết quả
+-------------+-------------------------------------------------------+ | StudentName | FormattedOutput | +-------------+-------------------------------------------------------+ | Adam | Learning Java,Learning Spring and Hibernate Framework | | Bob | Learning C | | Carol | Learning MySQL from basic | +-------------+-------------------------------------------------------+ 3 rows in set (0.00 sec)
Các tùy chọn GROUP_CONCAT:
SEPARATOR ',': Dấu phân cách (mặc định là ',')ORDER BY Title: Sắp xếp trước khi gom:GROUP_CONCAT(Title ORDER BY Title SEPARATOR ';')DISTINCT: Loại trùng lặp:GROUP_CONCAT(DISTINCT Title)group_concat_max_len: Giới hạn độ dài kết quả (mặc định 1024 byte), tăng nếu cần:SET SESSION group_concat_max_len = 1000000;
Ứng dụng: Xuất báo cáo, tạo CSV, JSON aggregation (kết hợp CONCAT), danh sách tag, category.