PHP代码
[U]复制代码[/U] 代码如下:
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代码
[U]复制代码[/U] 代码如下:
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代码
[U]复制代码[/U] 代码如下:
$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']);
分隔符还可以自定义,默认是以“,”作为分隔符,若要改为“作者: yj1281 时间: 2018-2-14 09:24
”,则使用SEPARATOR来指定,例如:
SQL代码
[U]复制代码[/U] 代码如下:
SELECT student_id, GROUP_CONCAT(courses_id SEPARATOR '作者: 新格网络 时间: 2018-2-14 09:24
') AS courses FROM student_courses WHERE student_id=2 GROUP BY student_id;
除此之外,还可以对这个组的值来进行排序再连接成字符串,例如按courses_id降序来排:
SQL代码
[U]复制代码[/U] 代码如下:
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;