於 MySQL 內, 資料格式如下:
id name
1 A
1 B
1 C
2 D
想要一行指令: "SELECT * FROM TABLE WHERE id = 1 GROUP BY id", 取得 GROUP BY id 的所有資料集合, 要怎麼做?
註: 想要內容列出 id=1, name=A,B,C
MySQL 為 GROUP BY 搭配的 GROUP_CONCAT() 功能
想要一行 SQL 做到 GROUP BY 並且 把資料全部合併成一行, 於是去 MySQL 找 Group by 的相關 function, 於是就找到了 GROUP_CONCAT().
參數說明: GROUP_CONCAT([DISTINCT] 要連接得字串 [Order BY ASC/DESC 排序字串] [Separator '分隔符號'])
官方說明: MySQL :: 12.16.1 GROUP BY (Aggregate) Functions
GROUP_CONCAT([DISTINCT] expr [,expr ...]
[ORDER BY {unsigned_integer | col_name | expr}
[ASC | DESC] [,col_name ...]]
[SEPARATOR str_val])mysql> SELECT student_name,
-> GROUP_CONCAT(test_score)
-> FROM student
-> GROUP BY student_name;Or:
mysql> SELECT student_name,
-> GROUP_CONCAT(DISTINCT test_score
-> ORDER BY test_score DESC SEPARATOR ' ')
-> FROM student
-> GROUP BY student_name;
於是指令如下:
- SELECT GROUP_CONCAT(name) as name, id FROM table GROUP BY id ORDER BY id
此行指令就會產出下述結果
- id=1, name=A,B,C
- id=2, name=D
註: GROUP_CONCAT() 預設會將資料用 "," 隔開合併起來, 還有更進階可以把 "," 換掉、排序等等, 就請再自行看說明文件囉~