需要来自3个不同表的SQL结果

时间:2012-10-29 18:17:56

标签: php mysql 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)显示结果。 任何人都可以帮忙??

我希望这很清楚......

谢谢!!

叶兰。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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