Home > Database > Mysql Tutorial > How Can I Remove Duplicates from MySQL's GROUP_CONCAT() Function?

How Can I Remove Duplicates from MySQL's GROUP_CONCAT() Function?

Susan Sarandon
Release: 2024-12-26 13:29:09
Original
772 people have browsed it

How Can I Remove Duplicates from MySQL's GROUP_CONCAT() Function?

Eliminate Duplicates from GROUP_CONCAT() using DISTINCT

In MySQL, GROUP_CONCAT() is a useful function for aggregating values from multiple rows into a single comma-separated string. However, when working with non-unique values, duplicates can appear in the resulting string. To address this, the DISTINCT attribute can be used within the GROUP_CONCAT() function.

Problem:

Consider the following sample data table with a "categories" column:

categories
test1 test2 test3
test4
test1 test3
test1 test3

When performing the following GROUP_CONCAT() query:

SELECT GROUP_CONCAT(categories SEPARATOR ' ') FROM table
Copy after login

The result is:

test1 test2 test3 test4 test1 test3
Copy after login

However, the desired result is:

test1 test2 test3 test4
Copy after login
Copy after login

Solution:

To eliminate duplicate values from the GROUP_CONCAT() result, use the DISTINCT attribute as follows:

SELECT GROUP_CONCAT(DISTINCT categories ORDER BY categories ASC SEPARATOR ' ') FROM table
Copy after login

The DISTINCT attribute ensures that only unique values are included in the concatenated string. The ORDER BY clause is used to sort the values in ascending order. The result is a comma-separated string containing only the distinct categories:

test1 test2 test3 test4
Copy after login
Copy after login

The above is the detailed content of How Can I Remove Duplicates from MySQL's GROUP_CONCAT() Function?. 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