我有四张桌子 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
答案 0 :(得分:1)
假设列thread_id
位于tbl_comments
表中,请将第一个where
更改为and
:
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
的表,但您的示例中没有显示任何对它的引用。
答案 1 :(得分: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