Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Gom nhóm danh sách giá trị thành một hàng dùng GROUP_CONCAT trong MySQL

Hàm GROUP_CONCAT() nối chuỗi các giá trị trong nhóm thành một chuỗi duy nhất, phân cách bằng dấu phẩy (mặc định).

Ví dụ

Tạo bảng sản phẩm có thể trùng ProductId:

mysql> create table DemoTable ( 
    ProductId int, 
    ProductName varchar(40), 
    ProductCategory varchar(40) 
); 
Query OK, 0 rows affected (0.67 sec)
mysql> insert into DemoTable values(100,'Product-1','1Product'); 
Query OK, 1 row affected (0.11 sec) 
mysql> insert into DemoTable values(101,'Product-2','2Product'); 
Query OK, 1 row affected (0.12 sec) 
mysql> insert into DemoTable values(100,'Product-1','3Product'); 
Query OK, 1 row affected (0.14 sec)

Dữ liệu gốc (3 hàng):

+-----------+-------------+-----------------+
| ProductId | ProductName | ProductCategory |
+-----------+-------------+-----------------+
| 100       | Product-1   | 1Product        |
| 101       | Product-2   | 2Product        |
| 100       | Product-1   | 3Product        |
+-----------+-------------+-----------------+

Gom nhóm theo ProductId

mysql> select ProductId, group_concat(ProductCategory) AS `GROUP` FROM DemoTable group by ProductId;
+-----------+-------------------+
| ProductId | GROUP             |
+-----------+-------------------+
| 100       | 1Product,3Product |
| 101       | 2Product          |
+-----------+-------------------+

Tùy chọn hữu ích:

  • SEPARATOR '; ' - đổi dấu phân cách
  • ORDER BY ProductCategory - sắp xếp trong nhóm
  • DISTINCT - loại trùng lặp
GROUP_CONCAT(DISTINCT ProductCategory ORDER BY ProductCategory SEPARATOR '; ')

Lưu ý: Độ dài tối đa mặc định là 1024 byte (biến group_concat_max_len).