"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Control the Order of Values in a MySQL GROUP_CONCAT Statement?

How Can I Control the Order of Values in a MySQL GROUP_CONCAT Statement?

Published on 2024-11-15
Browse:870

How Can I Control the Order of Values in a MySQL GROUP_CONCAT Statement?

Ordering Values in a GROUP_CONCAT Statement

In MySQL, GROUP_CONCAT combines values from one column based on a specific grouping. However, the order of the concatenated values is typically determined by the order in which the grouping occurs. To control the sorting of these values, a specific syntax is required.

To sort the concatenated values in a GROUP_CONCAT statement, use an ORDER BY clause within the nested query. For example, consider the following query:

GROUP_CONCAT((SELECT GROUP_CONCAT(parent.name SEPARATOR " » ") 
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 
ORDER BY parent.lft) SEPARATOR "<br />\n") AS competences

To sort the concatenated competence values in ascending order, modify the query as follows:

GROUP_CONCAT((SELECT GROUP_CONCAT(parent.name SEPARATOR " » ") 
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 
ORDER BY parent.lft ASC) SEPARATOR "<br />\n") AS competences

Similarly, to sort the values in descending order, use a DESC keyword after ASC:

GROUP_CONCAT((SELECT GROUP_CONCAT(parent.name SEPARATOR " » ") 
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 
ORDER BY parent.lft DESC) SEPARATOR "<br />\n") AS competences
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3