我对此SQL Fiddle有两个问题:
1。)为什么第2行不在结果列表中。
2.。)在生产(mysql 5.7)上我收到了错误
SELECT list包含nonaggregated列,这与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 |
答案 0 :(得分:0)
如果您需要按照帖子分组标记,则应使用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