2013-03-03 93 views
3

我已經四個表 1. tbl_threads 2. tbl_comments 3. tbl_votes 4. tbl_users三表INNER JOIN和WHERE子句

假設當前在USER_ID = 3 的thread_id = 10

記錄現在我必須檢索以下數據

All the fields from tbl_comments where tbl_comments.thread_id =10 
All the fields from tbl_users based on the common key tbl_users.user_id = tbl_comments.user_id 
All the fields from tbl_votes Where user_id =3 And tbl_votes.comment_id =tbl_comments.comment_id 

如何使用單個查詢執行所有此功能?

我曾嘗試以下查詢,但它給了我錯誤的結果

SELECT tbl_comments.* 
    , tbl_users.* 
    , tbl_votes.* 
FROM tbl_comments 
INNER JOIN tbl_users 
on tbl_comments.user_id = tbl_users.user_id 
WHERE thread_id= 10 
INNER JOIN tbl_votes 
on tbl_votes.comment_id = tbl_comments.comment_id 
WHERE tbl_votes.user_id= 3 
+0

告訴我們你得到了什麼 – 2013-03-03 17:13:27

+0

請修改您的問題並告訴我們您嘗試了些什麼。你還沒有提到關於tbl_users – DevelopmentIsMyPassion 2013-03-03 17:13:56

+0

這個查詢是否運行?它如何返回錯誤的結果?您當前的查詢不會選擇user_id = 3的位置,並且您有衝突的thread_id值。 – Byron 2013-03-03 17:32:21

回答

1

假設列thread_id是在tbl_comments表,改變第一whereand

SELECT tbl_comments.* 
    , tbl_users.* 
    , tbl_votes.* 
FROM tbl_comments 
INNER JOIN tbl_users 
on tbl_comments.user_id = tbl_users.user_id 
and tbl_comments.thread_id= 10 
INNER JOIN tbl_votes 
on tbl_votes.comment_id = tbl_comments.comment_id 
WHERE tbl_votes.user_id= 3 

雖然你的問題提到了一個名爲tbl_threads的表,你沒有在你的例子中顯示任何引用。

0
SELECT O.OrderNumber, CONVERT(date,O.OrderDate) AS Date, 
     P.ProductName, I.Quantity, I.UnitPrice 
    FROM [Order] O 
    JOIN OrderItem I ON O.Id = I.OrderId 
    JOIN Product P ON P.Id = I.ProductId 
ORDER BY O.OrderNumber