GROUP_CONCAT
函数用于将一列的多个值连接为一个字符串,并可以选择使用分隔符来分隔这些值。
语法:
GROUP_CONCAT([DISTINCT] expr [,expr ...]
[ORDER BY {unsigned_integer | col_name | expr}
[ASC | DESC] [,col_name ...]]
[SEPARATOR str_val])
参数说明:
DISTINCT
:可选参数,用于去除重复的值。expr
:要连接的列或表达式。ORDER BY
:可选参数,用于排序连接后的值。ASC
或 DESC
:可选参数,用于指定排序的顺序,默认为升序排序。SEPARATOR
:可选参数,用于指定连接的分隔符,默认为逗号 ,
。示例:
假设有以下 students
表:
id | name | subject |
---|---|---|
1 | John | Math |
2 | Jane | Science |
3 | Alice | Math |
4 | Bob | History |
5 | Tom | Science |
SELECT GROUP_CONCAT(name) AS all_names FROM students;
输出:John,Jane,Alice,Bob,Tom
SELECT GROUP_CONCAT(name SEPARATOR ';') AS all_names FROM students;
输出:John;Jane;Alice;Bob;Tom
SELECT GROUP_CONCAT(DISTINCT subject ORDER BY subject ASC) AS all_subjects FROM students;
输出:History,Math,Science