如何加入2个表来获得1个表?

时间:2013-07-19 07:13:24

标签: mysql sql

如何查询?我不知道!!

表1

userID | Name
0001   | Tim
0002   | James
0003   | Bond
0004   | Steve 
0005   | Bill

表2

ProductID | BuyerID | SellerID
00001     | 0001    | ooo4
00002     | 0003    | 0005
00003     | 0001    | 0002

如何将这两者结合起来:

ProductID | Buyer | Seller
00001     | Tim     | Steve
00002     | Bond    | Bill
00003     | Tim     | James

2 个答案:

答案 0 :(得分:2)

这样的东西
SELECT  p.ProductID,
        b.Name as Buyer,
        s.Name Seller
FROm    Table2 p LEFT JOIN
        Table1 b    ON  p.BuyerID = b.userID LEFT JOIN
        Table1 s    ON  p.SellerID = s.userID

SQL Fiddle DEMO

答案 1 :(得分:2)

SELECT
   tbl2.ProductID as ProductID, 
   Buyer.Name as Buyer, 
   Seller.Name as Seller
FROM tbl2
   LEFT JOIN tbl1 Buyer ON tbl2.BuyerID = Buyer.userID
   LEFT JOIN tbl1 Seller ON tbl2.BuyerID = Seller.userID