【问题标题】:mysql multiple group_concat order preservationmysql多个group_concat命令保存
【发布时间】:2014-08-26 12:18:01
【问题描述】:

假设我有一张桌子mytable

select * from mytable:

+------+------+------+ | a | b | c | +------+------+------+ | 1 | 1 | a | | 1 | 2 | b | +------+------+------+ 我想将列 bcgroup_concat 函数分组:

select a, group_concat(b), group_concat(c) from mytable group by a

+------+-----------------+-----------------+ | a | group_concat(b) | group_concat(c) | +------+-----------------+-----------------+ | 1 | 1,2 | a,b | +------+-----------------+-----------------+ 我的问题是,做 mysql 保证,group_concat 将始终保持相同的顺序,我不会在第二列中得到像 1、2b 这样的结果,一个在第三列?

【问题讨论】:

    标签: mysql sql group-by group-concat


    【解决方案1】:

    您可以在GROUP_CONCAT 函数中使用ORDER BY 子句:

    SELECT a, 
        GROUP_CONCAT(b ORDER BY b), 
        GROUP_CONCAT(c ORDER BY c)
    FROM mytable GROUP BY a
    

    【讨论】:

      【解决方案2】:

      如果不指定order by,则无法保证订单,这也是group_concat() 拥有自己的order by clause 的原因。根据 MySQL Spec,语法如下

      GROUP_CONCAT([DISTINCT] expr [,expr ...]
                   [ORDER BY {unsigned_integer | col_name | expr}
                       [ASC | DESC] [,col_name ...]]
                   [SEPARATOR str_val])
      

      因此,如果您想确定订单,请指定 order by 喜欢

      select a, 
      group_concat(b order by b desc) as b_concat, 
      group_concat(c order by c desc) as c_concat
      from mytable 
      group by a
      

      【讨论】:

        猜你喜欢
        • 2012-09-28
        • 2019-04-28
        • 2015-04-05
        • 2017-12-19
        • 1970-01-01
        • 2017-08-08
        • 2013-09-21
        • 1970-01-01
        • 2017-03-31
        相关资源
        最近更新 更多