2012-10-29 53 views
-1

您好!需要來自3個不同表格的SQL結果

這可能對SQL專家一個簡單的問題,以下是我有表:

**Table1 (Users):** 
UserId -> 0,1,2... 
UserName -> name1, name2, name3 ... 

**Table2 (Actions):** 
DealId -> 80,81,82... 
BuyerId -> 0,1,2... 
SellerId -> 2,3,4... 
Amount -> 80,120,900... 

**Table3 (Deals):** 
DealId -> 80,81,82... 
Dealname -> DealName1,DealName2... 
UserId -> 0,1,2... 

,這裏是結果表,我需要(從3個表):

Column 1: Buyer Name(Users.UserName) with (Actions.BuyerId -> Users.UserId) 
Column 2: Seller Name(Users.UserName) with (Actions.SellerId -> Users.UserId) 
column 3: Deal Name(Deals.DealName) with (Deals.DealId -> 80 [known number]) 
column 4: Amount (Actions.Amount) with (Deals.DealId -> 80 [known number]) 

當然我需要顯示只有結果與正確的DealId(80).. 任何人都可以幫忙?

我希望這是明確的..

謝謝!!

伊蘭。

+0

[你嘗試過什麼?](http://whathaveyoutried.com/) – ruakh

+2

這是不是 「給我德codez」 網站。 – CoffeeRain

+0

如果你不能幫助,請不要。 – EranLevi

回答

7
SELECT [Buyer].UserName, 
     [Seller].UserName, 
     [Deals].Dealname, 
     [Actions].Amount 
FROM [Deals] 
LEFT JOIN [Actions] ON [Actions].DealID = [Deals].DealID 
LEFT JOIN [Users] AS [Seller] ON [Seller].UserID = [Actions].SellerID 
LEFT JOIN [Users] AS [Buyer] ON [Buyer].UserID = [Actions].BuyerId 
WHERE [Deals].DealID = 80 
+0

這是正確的!非常感謝你! – EranLevi

+0

不錯。祝你好運 !! –

1
SELECT Buyer.UsernName, Seller.UserName, Deals.Dealname, Action.Amount FROM Deals 
LEFT JOIN Actions ON Actions.DealID=Deals.DealID 
LEFT JOIN Users AS Seller ON Seller.UserID=Actions.UserID 
LEFT JOIN Users AS Buyer ON Buyer.UserID=Buyer.UserID 
WHERE Deals.DealID=80 
+1

此代碼不正確。在'Buyer.UserID = Buyer.UserID'上提供'LEFT JOIN'會返回不正確的結果。另外 - 沒有'Actions.UserID'。 –