📜  group_concat 只返回一行 - SQL (1)

📅  最后修改于: 2023-12-03 15:15:26.681000             🧑  作者: Mango

Introduction to group_concat returning one row - SQL

In SQL, the GROUP_CONCAT() function is used to concatenate rows of strings into a single string, with the option to specify a separator between the values. However, it may only return one row even if there are multiple rows in the original table.

Syntax

The basic syntax of the GROUP_CONCAT() function is:

GROUP_CONCAT([DISTINCT] expr [,expr ...]
             [ORDER BY {unsigned_integer | col_name | expr}
                 [ASC | DESC] [,col_name ...]]
             [SEPARATOR str_val])
  • DISTINCT: this optional keyword eliminates duplicate values before concatenating
  • expr: the expression to be concatenated (such as a column name or expression)
  • ORDER BY: this optional syntax sorts the concatenated values according to the specified column or expression
  • ASC or DESC: optional sorting order
  • SEPARATOR: specifies the separator between values (default is comma)
Example

Suppose we have a students table with columns id, name, and major. We want to concatenate all the major names of the students into a single string, separated by a semicolon.

SELECT GROUP_CONCAT(DISTINCT major ORDER BY major SEPARATOR '; ')
AS majors_list FROM students;

This returns:

majors_list
-----------
Biology; Business; Chemistry; Computer Science; Mathematics; Physics

Note that the DISTINCT keyword is used to eliminate duplicates, the ORDER BY clause sorts the majors alphabetically, and the SEPARATOR specifies the semicolon and space between the values.

Conclusion

The GROUP_CONCAT() function is a useful tool for combining multiple rows of data into a single string. However, be aware that it may only return one row if used incorrectly.