如何使用 ORDER BY 实现 group_concat

How to implement group_concat with ORDER BY

我有两个 tables :

菜单章节

id chapterName chapterOrder
1 integer 1
2 double 2

菜单单位

id chapter_id unitName unitsOrder
1 1 uN1 1
2 1 uN2 2
3 2 uN5 1
4 2 un7 2

我想要的是最后得到一个像下面这样的 table :

chapterName unit_names
integer uN1, uN2
double un5, uN7

我试过:

SELECT menuChapters.chapterName, 
          GROUP_CONCAT(menuUnits.unitName ORDER BY menuUnits.unitsOrder SEPARATOR ', ')
          FROM menuChapters
          LEFT JOIN menuUnits ON menuUnits.chapter_id = menuChapters.id
          WHERE menuChapters.class = '13' AND menuChapters.course = '31'
          GROUP BY menuChapters.chapterName
          ORDER BY menuChapters.chapterOrder

但我得到的 unit_names 顺序错误:

chapterName unit_names
integer uN2, uN1
double un7, uN5

我想要的是:

chapterName unit_names
integer uN1, uN2
double un5, uN7

GROUP_CONCAT() 与 ORDER BY 在这里工作。请检查此版本明智的查询。

-- MySQL (v5.6)
SELECT mc.chapterName
     , GROUP_CONCAT(mu.unitName ORDER BY mu.unitsOrder SEPARATOR ', ') unit_names
FROM menuChapters mc
LEFT JOIN menuUnits mu
       ON mc.id = mu.chapter_id
GROUP BY mc.chapterName
ORDER BY mc.chapterOrder; 

请检查 url https://dbfiddle.uk/?rdbms=mysql_5.6&fiddle=87a41d6b0d2316803636e6fdeae08a53

-- MySQL (v5.7 & v5.8)
SELECT mc.chapterName
     , GROUP_CONCAT(mu.unitName ORDER BY mu.unitsOrder SEPARATOR ', ') unit_names
FROM menuChapters mc
LEFT JOIN menuUnits mu
       ON mc.id = mu.chapter_id
GROUP BY mc.chapterName, mc.chapterOrder
ORDER BY mc.chapterOrder; 

请查看下方url

对于版本 5.8 https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=628c4fde8d17d61f1f3db7f3478a39ea

对于版本 5.7 https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=3405f8dea89b8033ad96037cb42ba5da