2013-03-03 64 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