语法:
GROUP_CONCAT([DISTINCT] expr [,expr ...] [ORDER BY {unsigned_integer | col_name | expr} [ASC |DESC] [,col_name ...]] [SEPARATOR str_val])
+------------+---------+
| student_id | courses |
+------------+---------+
| 2 | 3
| 2 | 4
| 2 | 5+------------+---------+
1.例如: SELECT student_id, GROUP_CONCAT(courses_id) AS courses FROM student_courses WHERE student_id=2GROUP BY student_id; +------------+---------+ | student_id | courses | +------------+---------+ | 2 | 3,4,5 | +------------+---------+ 这 就不需要用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']);
2.当然分隔符还可以自定义,默认是以“,”作为分隔符,若要改为“|||”,则使用SEPARAT