Home >Database >Mysql Tutorial >How to Sort Values in GROUP_CONCAT Statements?

How to Sort Values in GROUP_CONCAT Statements?

Linda Hamilton
Linda HamiltonOriginal
2024-11-19 19:02:02657browse

How to Sort Values in GROUP_CONCAT Statements?

Sorting Values in GROUP_CONCAT Statements

The GROUP_CONCAT function in MySQL enables you to concatenate values grouped by a specified column. However, by default, the values are not sorted. To address this, there is a straightforward solution.

Solution:

The syntax of GROUP_CONCAT with sorting capabilities is:

GROUP_CONCAT(DISTINCT <expression> ORDER BY <order_expression> <direction> SEPARATOR <separator>)

Where:

  • : The values to be concatenated
  • : The column or expression used for sorting
  • : The sorting direction (ASC or DESC)
  • : The delimiter used to separate the concatenated values

Example:

In the provided query, to sort the concatenated values alphabetically, you can modify it as follows:

GROUP_CONCAT((SELECT GROUP_CONCAT(parent.name SEPARATOR " &raquo; ") 
FROM test_competence AS node, test_competence AS parent 
WHERE node.lft BETWEEN parent.lft AND parent.rgt 
  AND node.id = l.competence 
  AND parent.id != 1 
GROUP BY parent.id
ORDER BY parent.name) SEPARATOR "<br />\n") AS competences

By specifying ORDER BY parent.name within the subquery, the values will be sorted alphabetically before being concatenated. This will output the desired result:


Administration » Organization

Crafts » Joinery


The above is the detailed content of How to Sort Values in GROUP_CONCAT Statements?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn