数据库
首页 > 数据库> > mysql – 在Group_concat内部排序

mysql – 在Group_concat内部排序

作者:互联网

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表现如此?如何产生预期的产量?

解决方法:

GROUP_CONCAT()内尝试ORDER BY

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

this SQLFiddle

标签:sql,mysql,group-by,sql-order-by,group-concat
来源: https://codeday.me/bug/20190831/1777563.html