文法:
GROUP_CONCAT([DISTINCT] expr [,expr ...][ORDER BY {unsigned_integer | col_name | expr}[ASC | DESC] [,col_name ...]][SEPARATOR str_val])
下面示範一下這個函數,先建立一個學生選課表student_courses,並填充一些測試資料。
SQL代碼 複製代碼 代碼如下:CREATE TABLE student_courses (
student_id INT UNSIGNED NOT NULL,
courses_id INT UNSIGNED NOT NULL,
KEY(student_id)
);
INSERT INTO student_courses VALUES (1, 1), (1, 2), (2, 3), (2, 4), (2, 5);
若要尋找學生ID為2所選的課程,則使用下面這條SQL:
SQL代碼 複製代碼 代碼如下:mysql> SELECT student_id, courses_id FROM student_courses WHERE student_id=2;
+------------+------------+
| student_id | courses_id |
+------------+------------+
| 2 | 3 |
| 2 | 4 |
| 2 | 5 |
+------------+------------+
3 rows IN SET (0.00 sec)
輸出結果有3條記錄,說明學生ID為2的學生選了3、4、5這3門課程。
放在PHP裡,必須用一個迴圈才能取到這3條記錄,如下所示:
PHP代碼 複製代碼 代碼如下:foreach ($pdo->query("SELECT student_id, courses_id FROM student_courses WHERE student_id=2") as $row) {
$result[] = $row['courses_id'];
}
而如果採用GROUP_CONCAT()函數和GROUP BY語句就顯得非常簡單了,如下所示:
SQL代碼 複製代碼 代碼如下:mysql> SELECT student_id, GROUP_CONCAT(courses_id) AS courses FROM student_courses WHERE student_id=2 GROUP BY student_id;
+------------+---------+
| student_id | courses |
+------------+---------+
| 2 | 3,4,5 |
+------------+---------+
1 row IN SET (0.00 sec)
這樣php裡處理就簡單了:
PHP代碼 複製代碼 代碼如下:$row = $pdo->query("SELECT student_id, GROUP_CONCAT(courses_id) AS courses FROM student_courses WHERE student_id=2 GROUP BY student_id");
$result = explode(',', $row['courses']);
分隔字元還可以自訂,預設是以“,”作為分隔字元,若要改為“|||”,則使用SEPARATOR來指定,例如:
SQL代碼 複製代碼 代碼如下:SELECT student_id, GROUP_CONCAT(courses_id SEPARATOR '|||') AS courses FROM student_courses WHERE student_id=2 GROUP BY student_id;
除此之外,還可以對這個組的值來進行排序再串連成字串,例如按courses_id降序來排:
SQL代碼 複製代碼 代碼如下:SELECT student_id, GROUP_CONCAT(courses_id ORDER BY courses_id DESC) AS courses FROM student_courses WHERE student_id=2 GROUP BY student_id;