使用MySQL,我可以执行以下操作:

SELECT hobbies FROM peoples_hobbies WHERE person_id = 5;

我的输出:

shopping
fishing
coding

但我只想要1行1列:

预期输出:

shopping, fishing, coding

原因是我从多个表中选择了多个值,在所有的连接之后,我得到了比我想要的多得多的行。

我在MySQL Doc上查找了一个函数,它看起来不像CONCAT或CONCAT_WS函数接受结果集。

这里有人知道怎么做吗?


当前回答

在sql server中,使用string_agg将行字段值透视为列:

select string_agg(field1, ', ') a FROM mytable 

or

select string_agg(field1, ', ') within group (order by field1 dsc) a FROM mytable group by field2

其他回答

您可以使用GROUP_CONCAT:

SELECT person_id,
   GROUP_CONCAT(hobbies SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;

正如Ludwig在评论中所说,您可以添加DISTINCT运算符以避免重复:

SELECT person_id,
   GROUP_CONCAT(DISTINCT hobbies SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;

正如Jan在他们的评论中所说,您也可以在使用ORDER BY将值内爆之前对其进行排序:

SELECT person_id, 
       GROUP_CONCAT(hobbies ORDER BY hobbies ASC SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;

正如Dag在评论中所说,结果有1024字节的限制。要解决此问题,请在查询之前运行此查询:

SET group_concat_max_len = 2048;

当然,您可以根据需要更改2048。要计算和分配值:

SET group_concat_max_len = CAST(
                     (SELECT SUM(LENGTH(hobbies)) + COUNT(*) * LENGTH(', ')
                           FROM peoples_hobbies
                           GROUP BY person_id) AS UNSIGNED);

试试看:

DECLARE @Hobbies NVARCHAR(200) = ' '

SELECT @Hobbies = @Hobbies + hobbies + ',' FROM peoples_hobbies WHERE person_id = 5;

TL;博士;

set @sql='';
set @result='';
set @separator=' union \r\n';
SELECT 
@sql:=concat('select ''',INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME  ,''' as col_name,',
INFORMATION_SCHEMA.COLUMNS.CHARACTER_MAXIMUM_LENGTH ,' as def_len ,' ,
'MAX(CHAR_LENGTH(',INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME , '))as  max_char_len',
' FROM ',
INFORMATION_SCHEMA.COLUMNS.TABLE_NAME
) as sql_piece, if(@result:=if(@result='',@sql,concat(@result,@separator,@sql)),'','') as dummy
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE 
INFORMATION_SCHEMA.COLUMNS.DATA_TYPE like '%char%'
and INFORMATION_SCHEMA.COLUMNS.TABLE_SCHEMA='xxx' 
and INFORMATION_SCHEMA.COLUMNS.TABLE_NAME='yyy';
select @result;

现在已经很晚了,但对于那些正在搜索“使用透视表将多个MySQL行连接到一个字段中”的人来说会很有帮助:)

查询:

SELECT pm.id, pm.name, GROUP_CONCAT(c.name) as channel_names
FROM payment_methods pm
LEFT JOIN payment_methods_channels_pivot pmcp ON pmcp.payment_method_id = pm.id
LEFT JOIN channels c ON c.id = pmcp.channel_id
GROUP BY pm.id

桌子

payment_methods 
  id  | name
  1   | PayPal

channels
  id  | name
  1   | Google
  2   | Faceook

payment_methods_channels_pivot
   payment_method_id | channel_id
   1                 |  1
   1                 |  2

输出:

有一个GROUP聚合函数GROUP_CONCAT。

通过设置GROUP_CONCAT_max_len参数,可以更改GROUP_CONCAT值的最大长度。

请参阅MySQL文档中的详细信息。