GROUP_CONCAT()是MySQL数据库提供的一个函数,通常跟GROUP BY一起使用。
语法:
GROUP_CONCAT([DISTINCT] expr [,expr ...]
[ORDER BY {unsigned_integer | col_name | expr}
[ASC | DESC] [,col_name ...]]
[SEPARATOR str_val])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 | +------------+---------+
$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']);SELECT student_id, GROUP_CONCAT(courses_id SEPARATOR '|||') AS courses FROM student_courses WHERE student_id=2 GROUP BY student_id; +------------+---------+ | student_id | courses | +------------+---------+ | 2 | 3|||4|||5 | +------------+---------+
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; +------------+---------+ | student_id | courses | +------------+---------+ | 2 | 5,4,3 | +------------+---------+