MySql 合併查詢記錄GROUP_CONCAT

  • GROUP_CONCAT()

  • 示例:
//表結構
CREATE TABLE `demo` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `a` int(11) DEFAULT '0',
  `b` varchar(50) DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

//示例數據
id|a|b
1|1002|test
2|1001|test
select 
    GROUP_CONCAT(`a` SEPARATOR ',') as `a`,
    GROUP_CONCAT(`b` SEPARATOR ',') as `b`
from demo;

//結果
a|b
1002,1001|test,test
select 
    GROUP_CONCAT(`a` ORDER BY `a` asc SEPARATOR ',') as `a`, -- 使用order by 排序
    GROUP_CONCAT(DISTINCT `b` SEPARATOR ',') as `b` -- 使用 distinct 去除重複數據
from demo;

//結果
a|b
1001,1002|test
  • 語法結構:
GROUP_CONCAT(
[ DISTINCT ] expr [,
expr...] [ 
ORDER BY { unsigned_integer | col_name | formula } [ ASC | DESC ] [,
col...] ] [ SEPARATOR str_val ]
  • 要點:
     * 通過使用 DISTINCT 可以排除重複值。
     * 如果希望對結果中的值進行排序,可以使用 ORDER BY 子句。
     * SEPARATOR: 一個字符串值,它被用於插入到結果值中。缺省爲一個逗號 (","),可以通過指定 SEPARATOR “” 完全地移除這個分隔符。
     * group_concat_max_len:可以設置一個最大的長度。
        > 語法: SET [SESSION | GLOBAL] group_concat_max_len = unsigned_integer;
     * 如果最大長度被設置,結果值未到達到該長度,則結果值會被增加到這個長度。
     * 如果分組的字符過長,可以對系統參數進行設置:SET @@global.group_concat_max_len=40000;
        > 注意:group_concat_max_len在MySQL的配置文件中是有默認值的!最大值爲1024,如果要想該函數按需求設置長度
        > * SET GLOBAL group_concat_max_len=-1;
        > 查看group_concat_max_len最大長度:show variables like 'group_concat_max_len';
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章