I want to create a view by joining three tables.
The schema is a bit complicated, and so for the sake of simplicity, I will mention only the tables and columns required for the problem.
There is a table sales
with two columns:
SaleID(pkey),
Buyer,
Amount.
The second table is purchases
with two columns:
PurchaseID(pkey),
Seller,
Amount.
I have a third table stockhistory
which keeps track of the flow of materials.
The schema of that table is:
Date,
PurchaseID(fkey to column PurchaseID, Purchases Table),
SalesID(fkey to column SalesID, Sales Table),
Amount(calculated amount inserted here).
Now, each of the stockhistory
records corresponds to either a record of Purchases
table or Sales
table, but not both or none.
I have a constraint for that purpose:
([salesid] IS NULL AND [purchaseid] IS NOT NULL OR [salesid] IS NOT NULL AND
[purchaseid] IS NULL)
Now, in the view StockReport
, I am trying to pull all records from stockhistory
table, and want to display the name of buyer or seller as is the case.
I have tried to write a SQL of the lines of:
SELECT StockHistory.date
, StockHistory.purchaseid
, StockHistory.salesid
, Purchases.seller
, Sales.buyer
WHERE StockHistory.purchaseid = Purchases.purchaseid
OR StockHistory.salesid = Sales.salesid
How can I do the same with LEFT JOIN
?