คำอธิบาย
ใช้ GROUP_CONCAT(DISTINCT ...) รวมค่าที่ไม่ซ้ำในแต่ละกลุ่ม คั่นด้วยจุลภาค
ขั้นตอนการสร้างตารางและข้อมูลตัวอย่าง
mysql> create table DemoTable(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
Name varchar(40),
Score int );
Query OK, 0 rows affected (0.53 sec)
การเพิ่มข้อมูล
mysql> insert into DemoTable(Name, Score) values('Chris', 56);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable(Name, Score) values('Robert', 78);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(Name, Score) values('Chris', 56);
Query OK, 1 row affected (0.42 sec)
mysql> insert into DemoTable(Name, Score) values('Bob', 89);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(Name, Score) values('Chris', 56);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable(Name, Score) values('Chris', 57);
Query OK, 1 row affected (0.13 sec)
แสดงข้อมูลทั้งหมด
mysql> select * from DemoTable;
ผลลัพธ์:
+----+--------+-------+ | Id | Name | Score | +----+--------+-------+ | 1 | Chris | 56 | | 2 | Robert | 78 | | 3 | Chris | 56 | | 4 | Bob | 89 | | 5 | Chris | 56 | | 6 | Chris | 57 | +----+--------+-------+ 6 rows in set (0.00 sec)
คิวรี่ GROUP_CONCAT DISTINCT
mysql> select Name, group_concat(DISTINCT Score separator ',') from DemoTable group by Name;
ผลลัพธ์
+--------+--------------------------------------------+ | Name | group_concat(DISTINCT Score separator ',') | +--------+--------------------------------------------+ | Bob | 89 | | Chris | 56,57 | | Robert | 78 | +--------+--------------------------------------------+ 3 rows in set (0.00 sec)
คำอธิบาย
- Chris มี Score 56 ซ้ำ 3 ครั้ง และ 57 1 ครั้ง → DISTINCT ให้ 56,57
- Robert และ Bob มีค่าไม่ซ้ำ อยู่ค่าเดียว
- Default Separator คือ จุลภาค (,) สามารถเปลี่ยนได้ด้วย SEPARATOR
ตัวเลือกเพิ่มเติม
-- เรียงลำดับค่าภายใน GROUP_CONCAT GROUP_CONCAT(DISTINCT Score ORDER BY Score SEPARATOR ',') -- เพิ่มความยาวสูงสุด (Default 1024) SET SESSION group_concat_max_len = 10000;