基本上问题是如何从这里得到:

foo_id   foo_name
1        A
1        B
2        C

:

foo_id   foo_name
1        A B
2        C

当前回答

SELECT id, GROUP_CONCAT(CAST(name as CHAR)) FROM table GROUP BY id

会给你一个逗号分隔的字符串

其他回答

SELECT id, GROUP_CONCAT(CAST(name as CHAR)) FROM table GROUP BY id

会给你一个逗号分隔的字符串

结果被截断为由group_concat_max_len系统变量提供的最大长度,该变量的默认值为1024个字符,因此我们首先执行:

SET group_concat_max_len=100000000;

然后,例如:

SELECT pub_id,GROUP_CONCAT(cate_id SEPARATOR ' ') FROM book_mast GROUP BY pub_id

伟大的答案。 我还遇到了NULLS的问题,并设法通过在GROUP_CONCAT中包含一个COALESCE来解决它。示例如下:

SELECT id, GROUP_CONCAT(COALESCE(name,'') SEPARATOR ' ') 
FROM table 
GROUP BY id;

希望这能帮助到其他人

SELECT id, GROUP_CONCAT(name SEPARATOR ' ') FROM table GROUP BY id;

:- In MySQL, you can get the concatenated values of expression combinations . To eliminate duplicate values, use the DISTINCT clause. To sort values in the result, use the ORDER BY clause. To sort in reverse order, add the DESC (descending) keyword to the name of the column you are sorting by in the ORDER BY clause. The default is ascending order; this may be specified explicitly using the ASC keyword. The default separator between values in a group is comma (“,”). To specify a separator explicitly, use SEPARATOR followed by the string literal value that should be inserted between group values. To eliminate the separator altogether, specify SEPARATOR ''.

GROUP_CONCAT([DISTINCT] expr [,expr ...]
             [ORDER BY {unsigned_integer | col_name | expr}
                 [ASC | DESC] [,col_name ...]]
             [SEPARATOR str_val])

OR

mysql> SELECT student_name,
    ->     GROUP_CONCAT(DISTINCT test_score
    ->               ORDER BY test_score DESC SEPARATOR ' ')
    ->     FROM student
    ->     GROUP BY student_name;
SELECT id, GROUP_CONCAT(name SEPARATOR ' ') FROM table GROUP BY id;

https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat

在上面的链接中,GROUP_CONCAT:该函数返回一个字符串结果,其中包含组中的非null值。如果没有非NULL值,则返回NULL。