Group_concat函数

春有百花秋望月,夏有凉风冬听雪,心中若无烦恼事,便是人生好时节,愿你晨有清逸暮有悠闲,梦随心动心随梦求,祝中秋节愉快!

group_concat函数实用度其实很广的,在你需要的时候你会发觉这是一个多么有用的函数啊。废话少说,先举例说明下这个函数:

mysql> desc test_group_concat;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | int(11) | YES | | NULL | |
| name | varchar(20) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)


mysql> select * from test_group_concat;
+------+------+
| id | name |
+------+------+
| 1 | 10 |
| 1 | 20 |
| 1 | 20 |
| 2 | 20 |
| 3 | 200 |
| 3 | 500 |
+------+------+
6 rows in set (0.00 sec)

这样一个表结构,这样的内容的test_group_concat表,实用group_concat函数看下效果吧;

mysql> select id,group_concat(name) from test_group_concat;
+------+---------------------+
| id | group_concat(name) |
+------+---------------------+
| 1 | 10,20,20,20,200,500 |
+------+---------------------+
1 row in set (0.01 sec)

1:它能把所有指定列的内容放到一个字段中。

mysql> select id ,group_concat(distinct name ) from test_group_concat;
+------+------------------------------+
| id | group_concat(distinct name ) |
+------+------------------------------+
| 1 | 10,20,200,500 |
+------+------------------------------+
1 row in set (0.00 sec)

2:在函数中加了个distinct关键之,它还是组合了所有的指定字段的内容,不过全是去重再组合。

mysql> select id,group_concat(name separator ';') from test_group_concat;
+------+----------------------------------+
| id | group_concat(name separator ';') |
+------+----------------------------------+
| 1 | 10;20;20;20;200;500 |
+------+----------------------------------+
1 row in set (0.00 sec)

3:实用了关键之separator,用来分隔每个值,也可以看出不使用它时的默认分隔符是“,”这个符号。当然你还可以实用换行符“\r\n”等。

mysql> select id,group_concat(name order by name desc) from test_group_concat;
+------+---------------------------------------+
| id | group_concat(name order by name desc) |
+------+---------------------------------------+
| 1 | 500,200,20,20,20,10 |
+------+---------------------------------------+
1 row in set (0.00 sec)

4:在函数中是用order by能够让组合在一起的值重新排序。

Group_concat函数的语法:

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



官方详细说明手册
URL: http://dev.mysql.com/doc/refman/5.1/en/group-by-functions.html

作者: shawn53   发布时间: 2010-09-21