group_concat()会计算哪些行属于同一组,将属于同一组的列显示出来,实现字段的列转行设置
语法:
GROUP_CONCAT([DISTINCT] expr [,expr ...]
[ORDER BY {unsigned_integer | col_name | expr}
[ASC | DESC] [,col_name ...]]
[SEPARATOR str_val])
mysql> select * from t_test;
+------+
| id |
+------+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
+------+
5 rows in set (0.00 sec)
以默认的逗号作为分隔符
mysql> select group_concat(id) from t_test;
+------------------+
| group_concat(id) |
+------------------+
| 1,2,3,4,5 |
+------------------+
1 row in set (0.00 sec)
order
mysql> select id,group_concat(name order by name desc) from t_test group by id;
separator
SELECT id,group_concat(name,separator ';') groups FROM t_test group by id;
+----+------------+
| id | groups |
+-------+---------+
| 1 | tom;Jim |
| 2 | hulu |
| 3 | Jack;opt |
| 4 | |
| 5 | Sam;phony;childish |
+---+---------------------+
注意:默认下,group_concat()长度为1024,
group_concat截取的结果 会发现 缺失,
修改参数方法:
set global group_concat_max_len = 102400;
或者修改 my.ini 中group_concat_max_len