http://dev.mysql.com/doc/refman/5.1/zh/optimization.html#group-by-optimization
01mysql> select * from aa;
02+------+------+
03| id| name |
04+------+------+
05|1 | 10|
06|1 | 20|
07|1 | 20|
08|2 | 20|
09|3 | 200 |
10|3 | 500 |
11+------+------+
12
136 rows in set (0.00 sec)
以id分组,把name字段的值打印在一行,逗号分隔(默认)
01mysql> select id,group_concat(name) from aa group by id;
02+------+--------------------+
03| id| group_concat(name) |
04+------+--------------------+
05|1 | 10,20,20|
06|2 | 20 |
07|3 | 200,500|
08+------+--------------------+
093 rows in set (0.00 sec)
10
11
以id分组,把name字段的值打印在一行,分号分隔
1mysql> select id,group_concat(name separator ';') from aa group by id;
2+------+----------------------------------+
3| id| group_concat(name separator ';') |
4+------+----------------------------------+
5|1 | 10;20;20 |
6|2 | 20|
7|3 | 200;500 |
8+------+----------------------------------+
93 rows in set (0.00 sec)
以id分组,把去冗余的name字段的值打印在一行, 逗号分隔
1mysql> select id,group_concat(distinct name) from aa group by id;
2+------+-----------------------------+
3| id| group_concat(distinct name) |
4+------+-----------------------------+
5|1 | 10,20|
6|2 | 20 |
7|3 | 200,500 |
8+------+-----------------------------+
93 rows in set (0.00 sec)
以id分组,把name字段的值打印在一行,逗号分隔,以name排倒序
1mysql> select id,group_concat(name order by name desc) from aa group by id;
2+------+---------------------------------------+
3| id| group_concat(name order by name desc) |
4+------+---------------------------------------+
5|1 | 20,20,10 |
6|2 | 20|
7|3 | 500,200|
8+------+---------------------------------------+
93 rows in set (0.00 sec)