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表现如此?如何产生预期的产出?
答案 0 :(得分:5)
ORDER BY
SELECT GROUP_CONCAT(ItemType ORDER BY ItemType) AS typesTomatch , MatchID
FROM Table3 GROUP BY MatchID;