2011-08-02 153 views
2

我想知道是否有方法通過另一列來訂購GROUP_CONCAT-ed列。這是我的例子:訂購GROUP_CONCAT列(MySQL)

用戶

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_order」一欄,這樣我就可以刪除該列,並有結果集是這樣的:

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

有什麼建議?

回答

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 
+0

完美!謝謝! – Steve