如何加入3个生成此结果的表?

时间:2018-06-07 15:50:56

标签: sql inner-join

我有3张桌子:

   Users             Requests           Orders
+-----------+     +-------------+     +---------+
| UserId    |<--->| RequesterId |<--->| BuyerId |
+-----------+     +-------------+     +---------+
| FirstName |     | RequestId   |
+ ----------+     +-------------+
| LastName  |
+-----------+

我正在尝试生成一个结果,在单个查询中显示请求者和买方的名称。

我想要达到的结果是:

+---------+-------------------+------------------+---------------+--------------+
|RequestId|Requester FirstName|Requester LastName|Buyer FirstName|Buyer LastName|
+---------+-------------------+------------------+---------------+--------------+

这是我的查询失败:

SELECT

 R.RequestID as 'Order #'
,U.FirstName as 'Requester First Name'
,U.LastName as 'Requester Last Name'
,U.FirstName as 'Buyer First Name'
,U.LastName as 'Buyer Last Name'

FROM Requests R

INNER JOIN Users U
ON R.RequesterId = U.UserId

INNER JOIN Orders O
ON U.UserId = O.BuyerID

显然我这样做完全错了,但我不知道它是什么。有人可以给我一个提示吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

您需要将用户视为两个单独的表,并调用一个U1和另一个U2。所以您的原始选择呼叫将是

U1.FirstName as 'Requester First Name'
,U1.LastName as 'Requester Last Name'
,U2.FirstName as 'Buyer First Name'
,U2.LastName as 'Buyer Last Name'

编辑:我还没有对此进行测试,所以不知道它是否有效,但试一试:

SELECT

 R.RequestID as 'Order #'
,U1.FirstName as 'Requester First Name'
,U1.LastName as 'Requester Last Name'
,U2.FirstName as 'Buyer First Name'
,U2.LastName as 'Buyer Last Name'

FROM Requests R

INNER JOIN Users U1
ON R.RequesterId = U1.UserId

INNER JOIN Orders O
ON R.RequesterId = O.BuyerID

INNER JOIN Users U2
ON O.BuyerID = U2.UserId

再次编辑:现在我已经阅读了一些评论,但我认为我的代码无效,因为我不认为我理解了表格中的BuyerID和RequesterID之间的区别。我想你需要在Orders表中有一个单独的字段来链接到Requester表,然后通过改变

来改变我的代码。
ON R.RequesterId = O.BuyerID

ON R.RequesterId = O.RequesterID