📅  最后修改于: 2023-12-03 15:03:04.731000             🧑  作者: Mango
MySQL is a popular Relational Database Management System (RDBMS) used to store and manage data. One of the useful functions available in MySQL is the GROUP_CONCAT
function, which concatenates a column's values from many rows into a single string. However, sometimes we might need to exclude duplicate values from our concatenated string, and that's where the DISTINCT
clause comes in.
GROUP_CONCAT(DISTINCT column_name ORDER BY column_name SEPARATOR ' ')
DISTINCT
: Excludes duplicate values from the concatenated string.column_name
: The name of the column to concatenate. You can also use expressions instead of column names.ORDER BY
: Orders the concatenated values before aggregation. This is optional.SEPARATOR
: The separator to use between the concatenated values. This is optional and defaults to ,
.Suppose we have a table called customers
with the following data:
| id | name | city | |----|--------|---------------| | 1 | Alice | San Francisco | | 2 | Bob | New York | | 3 | Alice | San Francisco | | 4 | Charlie| Los Angeles |
If we want to group the customers by their city and concatenate their names, we can use the following query:
SELECT city, GROUP_CONCAT(name SEPARATOR ', ') as customers
FROM customers
GROUP BY city;
This will give us the following result:
| city | customers | |---------------|------------------------| | San Francisco | Alice, Bob, Alice | | New York | Bob | | Los Angeles | Charlie |
Notice that the duplicate name "Alice" appears twice in the concatenated string for the "San Francisco" group.
If we want to exclude duplicate names from the concatenated string, we can add the DISTINCT
keyword after the GROUP_CONCAT
function:
SELECT city, GROUP_CONCAT(DISTINCT name SEPARATOR ', ') as customers
FROM customers
GROUP BY city;
This will give us the following result:
| city | customers | |---------------|------------------| | San Francisco | Alice, Bob | | New York | Bob | | Los Angeles | Charlie |
Notice that the duplicate name "Alice" is now excluded from the concatenated string, as we specified the DISTINCT
keyword.