group_concat
时间: 2023-09-09 15:09:51 浏览: 37
GROUP_CONCAT is a MySQL function that concatenates rows into a single string. It is often used in conjunction with the GROUP BY clause to group multiple rows into a single string value. The syntax for the GROUP_CONCAT function is as follows:
```
GROUP_CONCAT([DISTINCT] expr [,expr ...]
[ORDER BY {unsigned_integer | col_name | expr}
[ASC | DESC] [,col_name ...]]
[SEPARATOR str_val])
```
The DISTINCT keyword is optional and allows for the removal of duplicate values. The expr parameter specifies the column or expression to concatenate. The ORDER BY clause is also optional and allows for the sorting of the concatenated values. The SEPARATOR parameter specifies the delimiter to use between the concatenated values.
Example:
Suppose we have a table called `employees` with the following data:
```
id name department
1 John Sales
2 Jane Marketing
3 Bob Sales
4 Sue Marketing
```
If we want to concatenate all the names of employees in each department, we can use the following query:
```
SELECT department, GROUP_CONCAT(name SEPARATOR ', ')
FROM employees
GROUP BY department;
```
The output would be:
```
department GROUP_CONCAT(name SEPARATOR ', ')
Marketing Jane, Sue
Sales John, Bob
```
Note that the values in the GROUP_CONCAT column are separated by a comma and a space (', ').