GROUP_CONCAT基于辅助表排序

时间:2019-03-05 14:21:36

标签: mysql sql

是否可以根据辅助表对GROUP_CONCAT进行排序?

我有3张桌子,其设置类似于:

users          usersPrivilegeGroups     privilegeGroupsPriority
-----------    ---------------------    -----------------------
userid PK      groupName FK             groupName PK
username       userid FK                priority int
               active

使用以下内容,我将匹配的用户数据与相关的usersPrivilegeGroups.groupName合并为一个字段:

SELECT
    users.*,
    GROUP_CONCAT(privList.groupName separator ',') AS privilegeGroups
FROM users
    LEFT JOIN usersPrivilegeGroups privList
    ON (privList.userid = users.userid AND privList.active = 1)
WHERE users.userid = ...

是否有一种基于privGroups升序对匹配的组(privilegeGroupsPriority.priority)进行排序的方法?

1 个答案:

答案 0 :(得分:2)

您需要JOIN优先级表并在ORDER BY内执行GROUP_CONCAT优先级值:

SELECT
    users.*,
    GROUP_CONCAT(privList.groupName separator ',' 
                 ORDER BY priority.priority ) AS privilegeGroups
FROM users

    LEFT JOIN usersPrivilegeGroups privList
    ON (privList.userid = users.userid AND privList.active = 1)

    LEFT JOIN privilegeGroupsPriority priority
    ON privList.groupName = priority.groupName

WHERE users.userid = ...