Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering in a MySQL GROUP_CONCAT with a function in it

Tags:

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 want 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?

like image 314
acme Avatar asked Oct 16 '09 12:10

acme


People also ask

How do you concatenate a group order?

Introduction to MySQL GROUP_CONCAT() functionThe ORDER BY clause allows you to sort the values in ascending or descending order before concatenating. By default, it sorts the values in ascending order. If you want to sort the values in the descending order, you need to specify explicitly the DESC option.

What is the difference between concat and Group_concat in MySQL?

The difference here is while CONCAT is used to combine values across columns, GROUP_CONCAT gives you the capability to combine values across rows. It's also important to note that both GROUP_CONCAT and CONCAT can be combined to return desired results.

What does Group_concat do in MySQL?

The GROUP_CONCAT() function in MySQL is used to concatenate data from multiple rows into one field. This is an aggregate (GROUP BY) function which returns a String value, if the group contains at least one non-NULL value. Otherwise, it returns NULL.

Can we use Group_concat in SQL Server?

GROUP_CONCAT is a function which concatenates/merges the data from multiple rows into one field. It is a GROUP BY function which returns a string if the group contains at least 1 non-null value, if it does not, it returns a Null value.


1 Answers

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.

like image 186
Jazzy Avatar answered Oct 08 '22 08:10

Jazzy