有关mysql中group_concat的用法举例
在对一批mysql数据进行迁移转换时,发现group_concat函数可以简单实现字段的列转行设置。
以下是我的实际操作过程,分享一下,供大家参考。
一,准备些测试数据
Database changed
mysql> select * from t_kenyon;
+------+
| id |
+------+
| 1 |
| 123 |
| 789 |
| 345 |
| 78 |
+------+
5 rows in set (0.00 sec)
二,操作步骤
1,以默认的逗号作为分隔符
+------------------+
| group_concat(id) |
+------------------+
| 1,123,789,345,78 |
+------------------+
1 row in set (0.00 sec)
2,对ID值进行排序后行转列
+------------------------------+
| group_concat(id order by id) |
+------------------------------+
| 1,78,123,345,789 |
+------------------------------+
1 row in set (0.00 sec)
3,使用其他分割符,如*和;等
+--------------------------------+
| group_concat(id separator '*') |
+--------------------------------+
| 1*123*789*345*78 |
+--------------------------------+
1 row in set (0.00 sec)
4,分隔符与排序结合起来用
+--------------------------------------------+
| group_concat(id order by id separator '_') |
+--------------------------------------------+
| 1_78_123_345_789 |
+--------------------------------------------+
1 row in set (0.00 sec)
5,对相同的值分组
mysql> insert into t_kenyon values (78);
Query OK, 1 row affected (0.00 sec)
mysql> select group_concat(id) from t_kenyon group by id;
+------------------+
| group_concat(id) |
+------------------+
| 1 |
| 78,78 |
| 123 |
| 345 |
| 789 |
+------------------+
5 rows in set (0.00 sec)
三,参数设置与限制说明
1.查看服务器中设置
+----------------------+-------+
| Variable_name | Value |
+----------------------+-------+
| group_concat_max_len | 1024 |
+----------------------+-------+
1 row in set (0.00 sec)
以上设置的值说明当前是默认长度1KB
2.改变参数值
方法一:修改配置文件中参数,新增 group_concat_max_len = 10240
方法二:在会话中实现,全局或当前session中
SET SESSION group_concat_max_len=10240;
就是这些了,希望对有缘的人有所帮助,哈!!
您可能感兴趣的文章:
有关mysql中group_concat的用法举例
mysql中group_concat函数用法
MySQL中group_concat函数使用例子
mysql递归查询替代函数实例
mysql DISTINCT关键字(用除重复数据)的用法
sql字段多个值查询的例子
mysql中的group_concat()函数
mysql去掉重复值的实例分享
mysql load data 用法举例(图文)
mysql中limit、order by和group by的用法实例解析