เมื่อต้องการจัดกลุ่มข้อมูลตามคอลัมน์หนึ่ง และแสดงข้อมูลจากอีกคอลัมน์หนึ่งรวมกันในแถวเดียว โดยคั่นด้วยตัวแบ่ง (separator) สามารถใช้ฟังก์ชัน GROUP_CONCAT() ร่วมกับ GROUP BY ได้
สร้างตารางตัวอย่าง
mysql> create table DemoTable (
PlayerId int,
ListOfPlayerName varchar(30) );
Query OK, 0 rows affected (0.52 sec)
เพิ่มข้อมูลตัวอย่าง
mysql> insert into DemoTable values(100,'Chris'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(101,'David'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(100,'Bob'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(100,'Sam'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(102,'Carol'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values(101,'Tom'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(102,'John'); Query OK, 1 row affected (0.12 sec)
แสดงข้อมูลทั้งหมด
mysql> select *from DemoTable;
ผลลัพธ์:
+----------+------------------+ | PlayerId | ListOfPlayerName | +----------+------------------+ | 100 | Chris | | 101 | David | | 100 | Bob | | 100 | Sam | | 102 | Carol | | 101 | Tom | | 102 | John | +----------+------------------+ 7 rows in set (0.00 sec)
คิวรี่จัดกลุ่มและรวมข้อมูลด้วย separator
mysql> select PlayerId,group_concat(ListOfPlayerName separator '/') as AllPlayerNameWithSameId from DemoTable
group by PlayerId;
ผลลัพธ์:
+----------+-------------------------+ | PlayerId | AllPlayerNameWithSameId | +----------+-------------------------+ | 100 | Chris/Bob/Sam | | 101 | David/Tom | | 102 | Carol/John | +----------+-------------------------+ 3 rows in set (0.00 sec)
คำอธิบายเพิ่มเติม
GROUP_CONCAT()ใช้รวมค่าจากหลายแถวเป็นสตริงเดียว- พารามิเตอร์
separatorระบุตัวคั่นระหว่างค่า (ค่าเริ่มต้นคือ comma) - สามารถเพิ่ม
ORDER BYภายใน GROUP_CONCAT ได้ เช่นGROUP_CONCAT(name ORDER BY name SEPARATOR ', ') - ค่าเริ่มต้นความยาวสูงสุดคือ 1024 ตัวอักษร สามารถปรับได้ด้วยตัวแปร
group_concat_max_len