2017-04-07 71 views
0

我對這個​​兩個問題導致:MySQL的:從毫米表昏迷分離柱

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 | 

回答

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