Home > Database > Mysql Tutorial > body text

How to Sort Values in GROUP_CONCAT Statements?

Linda Hamilton
Release: 2024-11-19 19:02:02
Original
561 people have browsed it

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>)
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template