Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

รวมรายการในกลุ่มเป็นแถวเดียวด้วย GROUP_CONCAT ใน MySQL

การใช้ GROUP_CONCAT() รวมค่าจากหลายแถวเป็นสตริงเดียวใน MySQL

ฟังก์ชัน GROUP_CONCAT() ใช้รวมค่าจากหลายแถวในกลุ่มเดียวกัน (GROUP BY) เป็นสตริงเดียว คั่นด้วยเครื่องหมายจุลภาค (หรือตัวคั่นที่กำหนด)

ตัวอย่างการใช้งาน

สร้างตารางสินค้าและหมวดหมู่:

mysql> create table DemoTable (
    ProductId int,
    ProductName varchar(40),
    ProductCategory varchar(40)
);

เพิ่มข้อมูล (ProductId 100 มี 2 หมวดหมู่):

mysql> insert into DemoTable values(100,'Product-1','1Product');
mysql> insert into DemoTable values(101,'Product-2','2Product');
mysql> insert into DemoTable values(100,'Product-1','3Product');

ข้อมูลต้นฉบับ:

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

คิวรีรวมหมวดหมู่ตาม ProductId:

mysql> select ProductId, group_concat(ProductCategory) AS `GROUP` FROM DemoTable group by ProductId;

ผลลัพธ์:

+-----------+-------------------+
| ProductId | GROUP             |
+-----------+-------------------+
| 100       | 1Product,3Product |
| 101       | 2Product          |
+-----------+-------------------+

ตัวเลือกเพิ่มเติมของ GROUP_CONCAT:

  • SEPARATOR '|' - เปลี่ยนตัวคั่น (ค่าเริ่มต้นคือ ',')
  • ORDER BY col - จัดเรียงค่าก่อนรวม
  • DISTINCT - ลบค่าซ้ำก่อนรวม

ตัวอย่าง: GROUP_CONCAT(DISTINCT ProductCategory ORDER BY ProductCategory SEPARATOR ' | ')

ข้อจำกัด: ความยาวสูงสุดควบคุมด้วยตัวแปร group_concat_max_len (ค่าเริ่มต้น 1024 ไบต์) อาจต้องเพิ่มค่าสำหรับข้อมูลเยอะ