Mysql,group by和subquery在一行中

时间:2014-01-28 07:38:57

标签: mysql subquery

我有3个表(内容,标签,contents_tags)。

可在http://sqlfiddle.com/#!2/8b0338

获取

我需要一个返回类似内容的查询:

+------------+--------+----------------+
| contents.id| title  | tag            |
+------------+--------+----------------+
|     1      | News 1 | News, Articles |
|     2      | News 2 | News           |
+------------+--------+----------------+

1 个答案:

答案 0 :(得分:2)

您可以使用join和group_concat

试试这个

select id, title, tag from contents 
join 
 (select id_content, GROUP_CONCAT(tag) as tag from contents_tags 
  join tags on contents_tags.id_tag=tags.id group by id_content) t on
contents.id=t.id_content