开发者

Ordering in a MySQL GROUP_CONCAT with a function in it

I want to order the results in a GROUP_CONCAT function. The problem is, that the selection in the GROUP_CONCAT-function is another function, like this (fantasy select):

SELECT a.name,
    GROUP_CONCAT(DISTINCT CONCAT_WS(':', b.id, c.name) ORDER BY b.id ASC) AS course
FROM people a, stuff b, courses c
GROUP BY a.id

I wan开发者_如何学Pythont to get a result like (ordered by b.id):

michael    1:science,2:maths,3:physics

but I get:

michael    2:maths,1:science,3:physics

Does anyone know how I can order by b.id in my group_concat here?


If anyone cares, I think I found a solution for at least a similar problem.

http://mahmudahsan.wordpress.com/2008/08/27/mysql-the-group_concat-function/

select GROUP_CONCAT(columnName order by someColumn SEPARATOR '|') from tableName where fieldId = p.id

The order by goes in the group_concat BEFORE the separator if there is one.


I know this is really old, but just now I was looking for an answer and @korny's answer gave me the idea for this:

SELECT a.name,
GROUP_CONCAT(DISTINCT CONCAT_WS(':', b.id, c.name) 
             ORDER BY CONCAT_WS(':', b.id, c.name) ASC) AS course
FROM people a, stuff b, courses c
GROUP BY a.id

(And it works for me, if that wasn't clear :-) )


I don't know of a standard way to do this. This query works, but I'm afraid it just depends on some implementation detail:

SELECT a_name, group_concat(b_id)
FROM (
    SELECT a.name AS a_name, b.id AS b_id
    FROM tbl1 a, tbl2 b
    ORDER BY a.name, b.id) a
GROUP BY a_name


No need for subselects.

SELECT people.name, CONCAT_WS(":", stuff.id, courses.name) data
FROM people, stuff, courses
ORDER BY stuff.id, people.name


SELECT pub_id,GROUP_CONCAT(DISTINCT cate_id)
FROM book_mast
GROUP BY pub_id
ORDER BY GROUP_CONCAT(DISTINCT cate_id) ASC;


SELECT generated.name, GROUP_CONCAT(generated.data)
FROM (
    SELECT people.name, CONCAST_WS(":", stuff.id, courses.name) data
    FROM people, stuff, courses
    ORDER BY stuff.id, people.name
) generated
GROUP BY generated.name
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜