使用GROUP_CONCAT語法
語法:
GROUP_CONCAT([DISTINCT] expr [,expr ...][ORDER BY {unsigned_integer | col_name | expr}[ASC | DESC] [,col_name ...]][SEPARATOR str_val])
下面演示一下這個函數,先建立一個學生選課表student_courses,並填充一些測試數據。
SQL代碼
Java代碼
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 );
www.2cto.com
若要查找學生ID為2所選的課程,則使用下面這條SQL:
Java代碼
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)
www.2cto.com
輸出結果有3條記錄,說明學生ID為2的學生選了3、4、5這3門課程。
放在PHP裡,必須用一個循環才能取到這3條記錄,如下所示:
PHP代碼
Java代碼
foreach ($pdo->query( "SELECT student_id, courses_id FROM student_courses WHERE student_id=2" ) as $row) {
$result[] = $row['courses_id' ];
}
www.2cto.com
而如果采用GROUP_CONCAT()函數和GROUP BY語句就顯得非常簡單了,如下所示:
SQL代碼
Java代碼
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代碼
Java代碼
$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代碼
Java代碼
SELECT student_id, GROUP_CONCAT(courses_id SEPARATOR '|||' ) AS courses FROM student_courses WHERE student_id= 2 GROUP BY student_id;
www.2cto.com
除此之外,還可以對這個組的值來進行排序再連接成字符串,例如按courses_id降序來排:
SQL代碼
Java代碼
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;