group concat - MySQL: result from mm table as coma separated column -


this question has answer here:

i have 2 questions sql fiddle:

1.) why row 2 not in result list.

2.) on production (mysql 5.7) got error

select list contains nonaggregated column incompatible 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 post values (1, "first post"); insert post values (2, "second post");  insert tag values (1, "sql"); insert tag values (2, "mm relation"); insert tag values (3, "group concat");  insert mm values (1, 1); insert mm values (1, 2); insert mm values (1, 3); 

query 1:

select    post.post_id,   post.name,    group_concat(t.tagname separator ',') tags    post  left join    mm on mm.post_id = post.post_id left join   tag t on t.tag_id = mm.tag_id 

results:

| post_id |       name |                         tags | |---------|------------|------------------------------| |       1 | first post | sql,mm relation,group concat | 

you should use group post.post_id if need tags grouped per post:

select    post.post_id,   post.name,    group_concat(t.tagname separator ',') tags    post  left join    mm on mm.post_id = post.post_id left join   tag t on t.tag_id = mm.tag_id group post.post_id 

and use distinct ensure unique keywords: http://sqlfiddle.com/#!9/e7c87e/12


Comments

Popular posts from this blog

How to understand 2 main() functions after using uftrace to profile the C++ program? -

c# - Update a combobox from a presenter (MVP) -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -