mysql - 将 SQL 结果与逗号分隔符结合起来

标签 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

谢谢

最佳答案

您可以使用group_concat但从结果连接有 1024 个字符的默认限制,剩余数据将被截断,但是可以通过以下手册增加此限制,但它也依赖于 max_allowed_packet也是

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)

关于mysql - 将 SQL 结果与逗号分隔符结合起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25603030/

相关文章:

php - 如何使用 MySQL 查询中的行创建 HTML 表格布局?

php - MySql PDO - 使用 GROUP BY、ORDER BY 和 INNER JOIN 时如何获取 "newest rows from group"?

mysql - MySQL 如何决定在 group by 子句中返回哪个 id?

php - Symfony2 插入错误参数[null,null,null]

涉及 group by 和 join 的 SQL 查询

java - Hibernate:如何选择除最后 N 行以外的所有行?

mysql - 选择sql中在一个属性上具有最大值且小于另一属性的记录

SQLite 滥用聚合 : SUM()

mysql查询获取根父级

php - 选择包含 Join 和 Count 的行