如何使这个MYSQL外连接工作

时间:2015-01-13 20:47:38

标签: mysql join outer-join

我有4张桌子:

comment (CommentID, StoryID, UserID, CommentContent), 
vote (VoteID, UserID, AnswerID), 
answer (AnswerID, StoryID, AnswerContent), 
user (UserID, Username)

所以我想得到故事8的所有评论以及发表这些评论的用户的信息(包括他们的投票信息)。并非所有发表评论的用户都会投票。所以这是我的查询,但它不起作用

SELECT * FROM comment a 
  LEFT JOIN vote b ON a.UserID = b.UserID 
  JOIN answer c ON b.AnswerID = c.AnswerID 
  JOIN user d ON a.UserId = d.UserID  
GROUP BY a.CommentID HAVING a.StoryID = 8

我不知道为什么此查询会显示未投票的评论者的投票结果。你能帮我解决一下吗?非常感谢你。

1 个答案:

答案 0 :(得分:0)

您的GROUP BY和HAVING条款不正确。

SELECT * FROM comment a 
  LEFT JOIN vote b ON a.UserID = b.UserID 
  JOIN answer c ON b.AnswerID = c.AnswerID
  WHERE a.StoryID = 8