Home > Database > Mysql Tutorial > How to Get Distinct Values with MySQL's GROUP_CONCAT()?

How to Get Distinct Values with MySQL's GROUP_CONCAT()?

Patricia Arquette
Release: 2024-12-08 22:29:11
Original
332 people have browsed it

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

With sample data:

categories
----------
test1 test2 test3
test4
test1 test3
test1 test3
Copy after login

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

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!

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