การใช้ GROUP_CONCAT() รวมค่าหลายแถวเป็นสตริงเดียว
GROUP_CONCAT() เป็น aggregate function ที่รวมค่าจากหลายแถวเป็นสตริงเดียว คั่นด้วย separator ที่กำหนด โดยไม่ต้องใช้ GROUP BY หากต้องการรวมทุกแถว
สร้างตารางและข้อมูล
mysql> create table DemoTable1371 (
-> Id int,
-> CountryName varchar(40)
-> );
Query OK, 0 rows affected (0.89 sec)
mysql> insert into DemoTable1371 values(100, 'US');
mysql> insert into DemoTable1371 values(100, 'UK');
mysql> insert into DemoTable1371 values(101, 'AUS');
mysql> insert into DemoTable1371 values(101, 'Angola');
ข้อมูลทั้งหมด
+------+-------------+ | Id | CountryName | +------+-------------+ | 100 | US | | 100 | UK | | 101 | AUS | | 101 | Angola | +------+-------------+
คำสั่ง GROUP_CONCAT โดยไม่มี GROUP BY
mysql> select group_concat(CountryName separator ',') from DemoTable1371;
ผลลัพธ์
+-----------------------------------------+ | group_concat(CountryName separator ',') | +-----------------------------------------+ | US,UK,AUS,Angola | +-----------------------------------------+
ตัวเลือกสำคัญของ GROUP_CONCAT
GROUP_CONCAT(
[DISTINCT] expr
[ORDER BY expr [ASC|DESC]]
[SEPARATOR str]
)
ตัวอย่างขั้นสูง
-- เรียงลำดับ ก่อนรวม SELECT GROUP_CONCAT(CountryName ORDER BY CountryName SEPARATOR ', ') FROM DemoTable1371; -- ผล: Angola, AUS, UK, US -- ลบซ้ำด้วย DISTINCT SELECT GROUP_CONCAT(DISTINCT CountryName SEPARATOR ', ') FROM DemoTable1371; -- รวมตามกลุ่ม (ใช้ GROUP BY) SELECT Id, GROUP_CONCAT(CountryName SEPARATOR ', ') FROM DemoTable1371 GROUP BY Id;
ข้อจำกัด: group_concat_max_len
ค่าเริ่มต้น 1024 ตัวอักษร หากข้อมูลเยอะจะถูกตัดทอน ต้องเพิ่ม:
SET SESSION group_concat_max_len = 1000000;
-- หรือใน my.cnf
[mysqld]
group_concat_max_len = 1000000
หมายเหตุ: GROUP_CONCAT() ส่งคืน NULL หากไม่มีแถว (หรือทุกแถวเป็น NULL) ใช้ COALESCE(GROUP_CONCAT(...), '') เพื่อให้ได้สตริงว่างแทน