开发者社区> 问答> 正文

【RDS】RDS MySQL实例时遇到group_concat函数问题,如何处理?

已解决

RDS MySQL实例时遇到group_concat函数问题,如何处理?

展开
收起
云上猫猫 2022-01-14 14:08:31 1479 0
1 条回答
写回答
取消 提交回答
  • 采纳回答

    group_concat返回结果的长度

    group_concat函数返回结果的长度受参数group_concat_max_len控制,默认值为1024,即默认返回1024字节长度的结果。具体参数值请参考如下:

    Dingtalk_20220114141010.jpg

    可以设置参数group_concat_max_len在全局生效或会话级别生效,以下是全局生效和会话级别生效的详细内容:

    • 全局生效:在控制台的参数设置页面修改。

    • 会话级别生效命令依次如下。其中第一个SQL语句是设置当前会话group_concat_max_len为90字节。第二个SQL语句是查看当前会话的group_concat_max_len值。第三个SQL语句是group_conca返回结果。第四个SQL语句是group_concat返回结果的长度。

    set group_concat_max_len=90;
    show variables like 'group_concat_max_len'; 
    select group_concat(distinct concat_ws(' ', t1.col0, t1.col2, t1.col3, t1.col4) separator "---")
    from grp_con_test t1,
         grp_con_test t2 \G
    select length(group_concat(distinct concat_ws(' ', t1.col0, t1.col2, t1.col3, t1.col4) separator "---"))
    from grp_con_test t1,
         grp_con_test t2 \G
    

    系统显示类似如下。

    6.png

    group_concat(distinct)去除重复数据失效的处理

    以下内容为重复数据失效的原因和解决方法。

    失效原因

    当设置group_concat_max_len为较大值时,使用group_concat(distinct)相关命令去除结果中的重复数据,会出现失效的情况,如下所示。

    select group_concat(distinct concat_ws(' ', t1.col0, t1.col2, t1.col3, t1.col4) separator "---")
    from grp_con_test t1,
       grp_con_test t2 \G
    

    系统显示类似如下,结果中出现了多个重复值,出现该问题的原因为,当group_concat返回结果集比较大,会出现内存临时表无法承载全部结果集数据,进而会使用磁盘临时表。而group_concat在使用磁盘临时表时会触发Bug,导致无法去除重复数据。

    7.png

    解决方法

    调整tmp_table_size参数设置,增大内存临时表的最大尺寸,依次执行以下SQL语句。其中第一个SQL语句是设置当前会话tmp_table_size为1MB。第二个SQL语句是查看当前会话tmp_table_size的设置。

    set tmp_table_size=1*1024*1024
    show variables like 'tmp_table_size'
    select group_concat(distinct concat_ws(' ', t1.col0, t1.col2, t1.col3, t1.col4) separator "---")
    from grp_con_test t1,
         grp_con_test t2 \G
    

    说明:也可以在RDS控制台的参数设置页面,修改tmp_table_size参数。

    group_concat和concat结合使用返回异常

    以下内容为group_concat和concat结合使用,返回异常的原因和解决方法。

    异常原因

    group_concat和concat结合使用某些情况下会出现返回BLOB字段类型的情况,如下所示。

    select concat('{', group_concat(concat('\"payMoney', t.signature, '\":', ifnull(t.money, 0))), '}') payType
    from my_money t
    where cash_id='989898989898998898'
    group by cash_id;
    

    系统显示类似如下,这是由于concat按字节返回结果,如果concat的输入有多种类型,其结果是不可预期的。

    8.png

    解决方法

    通过cast函数进行约束,concat返回结果为字符串类型,将上一节的例子修改为如下内容。

    select concat('{', cast(group_concat(concat('\"payMoney', t.signature, '\":', IFNULL(t.money, 0))) as char), '}') payType
    from my_money y t
    where cash_id='989898989898998898'
    group by cash_id;
    

    系统显示类似如下。

    9.png

    2022-01-14 14:13:40
    赞同 展开评论 打赏
来源圈子
更多
收录在圈子:
问答排行榜
最热
最新

相关电子书

更多
搭建电商项目架构连接MySQL 立即下载
搭建4层电商项目架构,实战连接MySQL 立即下载
PolarDB MySQL引擎重磅功能及产品能力盛大发布 立即下载

相关镜像