Home >Database >Mysql Tutorial >How to Get Distinct Values with MySQL's GROUP_CONCAT()?
MySQL GROUP_CONCAT() Distinct Values
When working with MySQL, it's common to aggregate data using the GROUP_CONCAT() function. However, what if you need to ensure that the concatenated results are distinct?
Let's consider the following scenario:
SELECT GROUP_CONCAT(categories SEPARATOR ' ') FROM table;
With sample data:
categories ---------- test1 test2 test3 test4 test1 test3 test1 test3
This query will return test1 test2 test3 test4 test1 test3. While this includes all the categories, it does not remove duplicates.
To obtain distinct values using GROUP_CONCAT(), MySQL provides the DISTINCT attribute. Adding DISTINCT to the query ensures that only distinct values are concatenated:
SELECT GROUP_CONCAT(DISTINCT categories ORDER BY categories ASC SEPARATOR ' ') FROM table;
By using DISTINCT, the duplicate values test1 test3 are removed, resulting in the desired output: test1 test2 test3 test4.
This modification not only eliminates duplicates but also sorts the concatenated values in ascending order, providing a more organized output.
The above is the detailed content of How to Get Distinct Values with MySQL's GROUP_CONCAT()?. For more information, please follow other related articles on the PHP Chinese website!