2013-04-17 154 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