使用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()函数的情况下应用字符串连接:

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()函数的情况下应用字符串连接:

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 )

使用MySQL(5.6.13)会话变量和赋值运算符,如下所示

SELECT @logmsg := CONCAT_ws(',',@logmsg,items) FROM temp_SplitFields a;

然后你可以得到

test1,test11

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

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

如果您的MySQL版本(4.1)支持GROUP_CONCAT,请查看GROUP_CONNAT。有关详细信息,请参阅文档。

它看起来像:

  SELECT GROUP_CONCAT(hobbies SEPARATOR ', ') 
  FROM peoples_hobbies 
  WHERE person_id = 5 
  GROUP BY 'all';

我有一个更复杂的查询,发现我必须在外部查询中使用GROUP_NCAT才能使其工作:

原始查询:

SELECT DISTINCT userID 
FROM event GROUP BY userID 
HAVING count(distinct(cohort))=2);

隐含的:

SELECT GROUP_CONCAT(sub.userID SEPARATOR ', ') 
FROM (SELECT DISTINCT userID FROM event 
GROUP BY userID HAVING count(distinct(cohort))=2) as sub;

希望这能帮助到某人。