mysql函式group_concat的使用
今天對一批資料要遷移轉換,查了下,有group_concat這個函式簡單實現欄位的列轉行設定,過程記錄如下
一.測試資料準備
mysql> use test;
database changed
mysql> select * from t_kenyon;
+------+
| id |
+------+
| 1 |
| 123 |
| 789 |
| 345 |
| 78 |
+------+
5 rows in set (0.00 sec)
二.使用經過 www.2cto.com
1.以預設的逗號作為分隔符
mysql> select group_concat(id) from t_kenyon;
+------------------+
| group_concat(id) |
+------------------+
| 1,123,789,345,78 |
+------------------+
1 row in set (0.00 sec)
2.對id值進行排序後行轉列
mysql> select group_concat(id order by id) from t_kenyon;
+------------------------------+
| group_concat(id order by id) |
+------------------------------+
| 1,78,123,345,789 |
+------------------------------+
1 row in set (0.00 sec)
3.使用其他分割符,如*和;等
mysql> select group_concat(id separator '*') from t_kenyon;
+--------------------------------+
| group_concat(id separator '*') |
+--------------------------------+
| 1*123*789*345*78 |
+--------------------------------+
1 row in set (0.00 sec) www.2cto.com
4.分隔符與排序結合起來用
mysql> select group_concat(id order by id separator '_') from t_kenyon;
+--------------------------------------------+
| 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.檢視伺服器中設定 www.2cto.com
mysql> show variables like '%group_concat%';
+----------------------+-------+
| variable_name | value |
+----------------------+-------+
| group_concat_max_len | 1024 |
+----------------------+-------+
1 row in set (0.00 sec)
以上設定的值說明當前是預設長度1kb
2.改變引數值
方法一:修改配置檔案中引數,新增 group_concat_max_len = 10240
方法二:在會話中實現,全域性或當前session中
set global group_concat_max_len=10240;
set session group_concat_max_len=10240;
作者 kenyon
mysql 奇數函式 MySQL常用函式
mysql運算子 比較運算子的結果是1 true 0 false 或null。這些函式可用於數字或者字串。expr between min and max 如果expr大於或者等於min,並且小於等於max,返回1,否則返回0。它等價於表示式 expr min and expr max expr i...
mysql 等待函式 mysql 內建函式
select convert 125.83 signed select cast 125.83 as signed 字串函式 檢視字元的ascii碼值ascii str str是空串時返回0 select ascii a 檢視ascii碼值對應的字元char 數字 select char 97 拼接...
mysql相關函式 MySql 相關函式
select group concat column name from table name group by table name,table name2.field 函式自定義排序 select from user where type in 1,2,3 order by field colu...