Search code examples
mysqlgroup-concat

MySQL: result from mm table as coma separated column


I have two questions about this SQL Fiddle:

1.) Why is row 2 not in the result list.

2.) On production (mysql 5.7) i got the error

SELECT list contains nonaggregated column this is incompatible with sql_mode=only_full_group_by ...

MySQL 5.6 Schema Setup:

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);

Query 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 |

Solution

  • You should use GROUP BY Post.post_id if you need to get the tags grouped per post:

    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
    

    And you could also use DISTINCT to ensure you only get unique keywords: http://sqlfiddle.com/#!9/e7c87e/12