将SQL结果与逗号分隔符组合在一起

时间:2014-09-01 09:46:04

标签: mysql sql

我需要将以下查询中的标记组合起来,用逗号分隔符分隔:

SQL

select question.text,tag.text
from question
left join q_t on question.id = q_t.wall_id
left join tag on q_t.tag_id = tag.id
where question.id in (1000001,1000002,1000003,1000004,1000005) 
order by field(question.id,1000001,1000002,1000003,1000004,1000005)

目前的结果:

text                         text
where is England?         Geography
where is England?         Continent
where is England?         general_knowledge
how many ...?             sport
how many ...?             Europe

要求的结果:

text                         text
where is England?         Geography,Continent,general_knowledge
how many ...?             sport,Europe

感谢,

1 个答案:

答案 0 :(得分:3)

您可以使用group_concat,但是有一个默认限制约为1024个字符,可以从结果中连接,剩下的数据将被截断,但是这个限制可以通过遵循手动来增加,但它也依赖于{{ 3}}

select question.text,group_concat(tag.text)
from question
left join q_t on question.id = q_t.wall_id
left join tag on q_t.tag_id = tag.id
where question.id in (1000001,1000002,1000003,1000004,1000005) 
group by  question.text
order by field(question.id,1000001,1000002,1000003,1000004,1000005)