【问题标题】:Order by inside Group_concat按 Group_concat 内部排序
【发布时间】:2013-07-24 21:43:12
【问题描述】:

This 是我的小提琴。

表和数据是

create table Table3 (MatchID varchar(10), ItemType varchar(10));
insert into Table3 values
('M001','Fruit'),
('M001','Animal'),
('M002','Fruit'),
('M002','Vehicle');

当您有一个按 MatchID 和 ItemType 排序的选择查询时,它正在返回

select MatchID,ItemType from Table3 order by MatchID,ItemType;

    MATCHID ITEMTYPE
    M001    Animal
    M001    Fruit
    M002    Fruit
    M002    Vehicle

像这样,这是意料之中的,也是正确的。

但是,当我 group_concated 时,它并没有以有序的方式返回。

Select group_concat(ItemType) as typesTomatch ,MatchID
from (select MatchID,ItemType from Table3 
      order by MatchID,ItemType)
c group by MatchID;

它正在返回

TYPESTOMATCH    MATCHID
Fruit,Animal    M001
Fruit,Vehicle   M002

出乎意料

TYPESTOMATCH    MATCHID
Animal,Fruit    M001
Fruit,Vehicle   M002

。为什么 group_concat 的行为如此?如何产生预期的输出?

【问题讨论】:

    标签: mysql sql group-by sql-order-by group-concat


    【解决方案1】:

    GROUP_CONCAT() 中尝试ORDER BY

    SELECT GROUP_CONCAT(ItemType ORDER BY ItemType) AS typesTomatch , MatchID
    FROM Table3 GROUP BY MatchID;
    

    this SQLFiddle

    【讨论】:

    • 你拯救了我的一天。不知道 GROUP_CONCAT() 内部的订单。太酷了
    • 你也踢出了一个结果集.. +1 for all
    猜你喜欢
    • 2015-09-26
    • 2010-12-26
    • 2016-05-31
    • 2019-03-25
    • 2020-05-14
    • 2013-04-12
    • 2017-07-07
    • 2014-12-09
    相关资源
    最近更新 更多