4

我有四个表 1. tbl_threads 2. tbl_comments 3. tbl_votes 4. tbl_users

假设当前登录的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
4

2 回答 2

2

假设列thread_idtbl_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,但您在示例中没有显示对它的任何引用。

于 2013-03-03T18:40:01.473 回答
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
于 2016-01-09T12:04:48.083 回答