Select 来自客户的买卖双方数据
Select buyers and sellers data from customer
我有两个表 Customer
和 Market
Select * from Customer
:
customer_id | f_name | l_name
-------------------------------
1 | Sam | Brow
2 | Alex | Fore
3 | Marc | Lor
4 | Fab | Sow
Select * from Market
Orderid | Product | SellerID | BuyerID
-----------------------------------------
5 | Apple | 1 | 2
6 | Juice | 3 | 4
执行此操作SELECT以获取买卖双方数据时,我拥有所有客户的数据。
SELECT c.f_name, c.l_name ,m.Orderid
FROM Customer c
INNER JOIN Market m ON m.BuyerID = c.customer_id OR m.SellerID = c.customer_id
相反,我需要将买家自己的数据和卖家自己的数据分开。我期待这样的事情:
Orderid | Seller_f_name | Buyer_f_name
----------------------------------------
5 | Sam | Alex
6 | Marc | Fab
有什么想法吗?
您需要与客户一起加入市场table两次table -
SELECT Orderid, C1.f_name Seller_f_name, C2.f_name Buyer_f_name
FROM Market M
LEFT JOIN Customer C1 ON M.SellerID = C1.customer_id
LEFT JOIN Customer C2 ON M.BuyerID = C2.customer_id;
我有两个表 Customer
和 Market
Select * from Customer
:
customer_id | f_name | l_name
-------------------------------
1 | Sam | Brow
2 | Alex | Fore
3 | Marc | Lor
4 | Fab | Sow
Select * from Market
Orderid | Product | SellerID | BuyerID
-----------------------------------------
5 | Apple | 1 | 2
6 | Juice | 3 | 4
执行此操作SELECT以获取买卖双方数据时,我拥有所有客户的数据。
SELECT c.f_name, c.l_name ,m.Orderid
FROM Customer c
INNER JOIN Market m ON m.BuyerID = c.customer_id OR m.SellerID = c.customer_id
相反,我需要将买家自己的数据和卖家自己的数据分开。我期待这样的事情:
Orderid | Seller_f_name | Buyer_f_name
----------------------------------------
5 | Sam | Alex
6 | Marc | Fab
有什么想法吗?
您需要与客户一起加入市场table两次table -
SELECT Orderid, C1.f_name Seller_f_name, C2.f_name Buyer_f_name
FROM Market M
LEFT JOIN Customer C1 ON M.SellerID = C1.customer_id
LEFT JOIN Customer C2 ON M.BuyerID = C2.customer_id;