MySQL函数-Group_Concat分组并行转列

group_concat函数解析:

1、concat()函数:

  功能:将多个字符串连接成一个字符串

  语法:concat(str1, str2)

  结果:连接参数str1,str2为一个字符串,如果有任何一个参数为null,则返回值为null

2、concat_ws()函数:

  功能:将多个字符串以指定分隔符形式连接成一个字符串,即concat with separator

  语法:concat_ws(separator, str1, str2)

  结果:str1/str2/str3,分隔符不能为null,如为null,返回结果也为null

3、group_concat()函数:

  功能:按照指定字段分组,将满足条件的行转列,可指定分隔符将所有满足条件的字符串连接成一个字符串,separator缺省时默认为","

  语法:

group_concat(Distinct 要连接的字段 Order BY 要排序的字段 asc/desc Separator ',')

  结果:通过distinct排除重复值;通过order by 对结果值进行排序;通过separator指定分隔符

现有需求:某一用户需同时拥有collections_id (a,b,c,d)才能拥有**权益

查询语句如下:

SELECT 
    uid, 
    group_concat(distinct collections_id order by collections_id separator ',') as cid,
    update_time
FROM user_collections 
where collections_id in (244,245,246,247) 
and state in(0,1,2,3)
group by uid
order by update_time;

查询结果如下:

注:当数据量太大,group_concat超出默认值1024后就会截断,查询出来的数据不全

解决方案:

1、查询当前mysql group_concat_max_len状态

show variables like 'group_concat_max_len';

2、在MySQL配置文件中添加配置:group_concat_max_len= -1(-1为最大值或根据实际需求设置长度),配置后重启MySQL服务

posted @ 2022-11-04 17:19  美女爱找茬  阅读(1080)  评论(0编辑  收藏  举报