2008年11月9日星期日

GROUP_CONCAT()妙用

GROUP_CONCAT()是MySQL数据库提供的一个函数,通常跟GROUP BY一起用,具体可参考MySQL官方文挡:http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat。

先来看一下这个函数的语法:

GROUP_CONCAT([DISTINCT] expr [,expr ...]
[ORDER BY {unsigned_integer | col_name | expr}
[ASC | DESC] [,col_name ...]]
[SEPARATOR str_val])

下面就演示一下这个函数所带来的方便之处,首先建立一个学生选课表student_courses,并填充一些测试数据。

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:

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语句就显得非常简单了,如下所示:

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来指定,例如:

mysql> 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 |
+------------+-----------+
1 row IN SET (0.00 sec)

除此之外,还可以对这个组的值来进行排序再连接成字符串,例如按courses_id降序来排:

mysql> 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 |
+------------+---------+
1 row IN SET (0.02 sec)

没有评论:

博客归档