MySQL:mm table 的结果作为逗号分隔列

MySQL: result from mm table as coma separated column

关于这个我有两个问题SQL Fiddle:

1.) 为什么第2行不在结果列表中。

2.) 在生产中 (mysql 5.7) 我得到了错误

SELECT 列表包含非聚合列,这与 sql_mode=only_full_group_by ...

不兼容

MySQL 5.6 架构设置:

CREATE TABLE MM(
  `post_id` int, 
  `tag_id` int
);

CREATE TABLE Post
(
  `post_id` int, 
  `name` varchar(200)
);

CREATE TABLE Tag(
  `tag_id` int, 
  `tagname` varchar(200)
);

Insert into Post values (1, "First Post");
Insert into Post values (2, "Second Post");

Insert into Tag values (1, "sql");
Insert into Tag values (2, "mm relation");
Insert into Tag values (3, "group concat");

Insert into mm values (1, 1);
Insert into mm values (1, 2);
Insert into mm values (1, 3);

查询 1:

Select 
  Post.post_id,
  Post.name, 
  GROUP_CONCAT(t.tagname SEPARATOR ',') as tags 
  from Post 
left join 
  MM on MM.post_id = Post.post_id
left join
  Tag as t on t.tag_id = MM.tag_id

Results:

| post_id |       name |                         tags |
|---------|------------|------------------------------|
|       1 | First Post | sql,mm relation,group concat |

如果您需要按照 post:

对标签进行分组,您应该使用 GROUP BY Post.post_id
Select 
  Post.post_id,
  Post.name, 
  GROUP_CONCAT(t.tagname SEPARATOR ',') as tags 
  from Post 
left join 
  MM on MM.post_id = Post.post_id
left join
  Tag as t on t.tag_id = MM.tag_id
GROUP BY Post.post_id

您还可以使用 DISTINCT 来确保您只获得唯一的关键字:http://sqlfiddle.com/#!9/e7c87e/12