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

SELECT hobbies FROM peoples_hobbies WHERE person_id = 5;

我的输出:

shopping
fishing
coding

但我只想要1行1列:

预期输出:

shopping, fishing, coding

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

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

这里有人知道怎么做吗?


当前回答

您可以使用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);

其他回答

这里,我的意图是在不使用group_concat()函数的情况下应用字符串连接:

Set @concatHobbies = '';
SELECT TRIM(LEADING ', ' FROM T.hobbies ) FROM 
(
   select 
   Id, @concatHobbies := concat_ws(', ',@concatHobbies,hobbies) as hobbies
   from peoples_hobbies
)T
Order by Id DESC
LIMIT 1

Here

   select 
   Id, @concatHobbies := concat_ws(', ',@concatHobbies,hobbies) as hobbies
   from peoples_hobbies

将返回

  Id    hobbies
  1     , shopping
  2     , shopping, fishing
  3     , shopping, fishing, coding

现在我们的预期结果是第三。所以我用

  Order by Id DESC 
  LIMIT 1
  

然后我也将第一个“,”从字符串中删除

 TRIM(LEADING ', ' FROM T.hobbies )

您可以使用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);

对于在这里查看如何将GROUP_NCAT与子查询一起使用的人,发布以下示例

SELECT i.*,
(SELECT GROUP_CONCAT(userid) FROM favourites f WHERE f.itemid = i.id) AS idlist
FROM items i
WHERE i.id = $someid

因此,必须在子查询中使用GROUP_CONNAT,而不是包装它。

有一个GROUP聚合函数GROUP_CONCAT。

在我的例子中,我有一行ID,必须将其转换为char,否则,结果被编码为二进制格式:

SELECT CAST(GROUP_CONCAT(field SEPARATOR ',') AS CHAR) FROM table