订购GROUP_CONCAT列(MySQL)

时间:2011-08-02 15:06:55

标签: mysql group-concat

我想知道是否有办法通过另一列订购GROUP_CONCAT-ed列。这是我的例子:

用户

 id | name
----+------------
  0 | John Smith

users_majors

user_id | major_id | order
--------+----------+-------
   0    |    2     |  1
   0    |    1     |  0

专业

 id | name
----+-------------
  0 | Biology
  1 | Chemistry
  2 | Engineering

这是我的疑问:

SELECT `users`.*, GROUP_CONCAT(DISTINCT `majors`.name) AS major, GROUP_CONCAT(DISTINCT `users_majors`.order) AS major_order
FROM `users`
LEFT JOIN users_majors ON (users_majors.user_id = users.id)
LEFT JOIN majors ON (majors.id = users_majors.major_id)
GROUP BY users.id

我按预期收到此结果集:

id | name        | major                 | major_order
---+-------------+-----------------------+-------------
 0 | John Smith  | Engineering,Chemistry | 1,0

我想要做的是让“major”列自动按“major_order”列排序,这样我就可以删除该列并使结果集看起来像这样:

id | name        | major
---+-------------+-----------------------
 0 | John Smith  | Chemistry,Engineering

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

GROUP_CONCAT包含ORDER BY选项。

SELECT `users`.*, GROUP_CONCAT(DISTINCT `majors`.name ORDER BY `users_majors`.order) AS major, GROUP_CONCAT(DISTINCT `users_majors`.order) AS major_order
FROM `users`
LEFT JOIN users_majors ON (users_majors.user_id = users.id)
LEFT JOIN majors ON (majors.id = users_majors.major_id)
GROUP BY users.id