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