SQL GROUP_CONCAT Function Explained
The GROUP_CONCAT function is used to combine multiple rows of data into one string with a specified delimiter. Its syntax is as follows:
GROUP_CONCAT([DISTINCT] expr [, expr ...]
[ORDER BY {unsigned_integer | col_name | expr}
[ASC | DESC] [, col_name ...]]
[SEPARATOR str_val])
Description of parameters:
- DISTINCT: an optional feature that removes duplicates, the function only returns unique values when DISTINCT is specified.
- Field to be merged, could be a column name, constant, or expression.
- ORDER BY: Optional parameter indicating the sorting rule before merging the data.
- ASC | DESC: Optional selection indicating the order of sorting, with the default being in ascending order.
- SEPARATOR: Optional choice that represents the separator used in the merged string, defaulting to a comma.
Suppose there is a table called students, which includes the following data:
+----+-------+---------+
| id | name | class |
+----+-------+---------+
| 1 | Alice | Math |
| 2 | Bob | English |
| 3 | Alice | Science |
+----+-------+---------+
The GROUP_CONCAT function can be used to merge the classes of students with the same name into one string. For example:
SELECT name, GROUP_CONCAT(class) AS classes
FROM students
GROUP BY name;
After executing the above query statement, the following results will be obtained:
+-------+-----------------+
| name | classes |
+-------+-----------------+
| Alice | Math,Science |
| Bob | English |
+-------+-----------------+
You can see that the classes of students with the same name have been combined into one string and separated by commas.