使用Left Join和Where IN子句的MYSQL查询

时间:2013-04-17 23:16:32

标签: mysql join left-join

我有三张桌子A B C,我试图从这三张桌子中检索信息。

A具有columnns userid头像用户名,B具有postid列,dateshared和C具有postid datecommented的列评论者。

我试图运行查询

Select  C.comment, C.commenter,  C.datecommented, B.postid, B.dateshared A.username A.avatar from B Left Join C  Left join A on C.postid = B.postid AND A.userid = C.commenter where B.postid IN ('1','2','3') order by  C.dateshared desc

但它会出现以下错误:

 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where B.postid IN ('1', '2', '3') order by C.dateshared '

任何人都可以指出我做错了什么或建议怎么做吗?

3 个答案:

答案 0 :(得分:2)

每个LEFT JOIN都需要自己的ON条件:

SELECT  C.comment, C.commenter, C.datecommented, B.postid, B.dateshared, A.username A.avatar
FROM    B
LEFT JOIN
        C
ON      C.postid = B.postid
LEFT JOIN
        A
ON      A.userid = C.commenter
WHERE   B.postid IN ('1','2','3')
ORDER BY
        C.dateshared desc

答案 1 :(得分:0)

我在您的示例查询中看到了几个问题:

  • 您在查询的第一部分中遗漏了一些逗号
  • 您没有为C
  • 指定任何加入条件

我会将其重写为:

    SELECT C.comment, C.commenter, C.datecommented, B.postid, B.dateshared, A.username, A.avatar 
    FROM B
    LEFT JOIN C ON C.postid = B.postid
    LEFT JOIN A ON A.userid = C.commenter
    WHERE B.postid IN ('1','2','3') 
    ORDER BY C.dateshared desc 

答案 2 :(得分:0)

这应该适合您,您的查询有一些语法错误:

Select  C.comment,C.commenter,C.datecommented,B.postid,B.dateshared,A.username,A.avatar
from B
Left Join C on C.postid = B.postid
Left join A on A.userid = C.commenter
where B.postid IN ('1','2','3')
order by  C.dateshared desc
相关问题