2013-04-17 171 views
2

我有三个表A B C,我试图从所有三个检索信息。MYSQL查询使用左连接和where IN子句

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 ' 

任何人都可以指出我在做什么错误或建议如何去做?

回答

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 
+0

工作就像曾为以及魅力 –

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 
+0

。 –

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