I have three tables (Stores, Item & StoreInv) and I am trying to do a join that contains all records from Stores & Items even if there are no matching records in StoreInv. Probably easiest to explain by an example:
Store table:
StoreId
-------
Store1
Store2
Store3
Item table:
ItemId
-------
A
B
C
StoreInv table (only contains records for Items with inventory at the store):
ItemId StoreId Qty
------- ------- ---
A Store1 6
B Store1 2
B Store2 4
Desired output:
StoreId ItemId Qty
------- ------ ---
Store1 A 6
Store2 A 0 (or null)
Store3 A 0 (or null)
Store1 B 2
Store2 B 4
Store3 B 0 (or null)
Store1 C 0 (or null)
Store2 C 0 (or null)
Store3 C 0 (or null)
What I have tried:
SELECT str.StoreId, itm.ItemId, inv.Qty
FROM Item itm
LEFT JOIN StoreInv inv ON inv.ItemId = itm.ItemId
RIGHT JOIN Stores str on str.StoreId = inv.StoreId
Result (not what I want):
StoreId ItemId Qty
------- ------ ---
Store1 A 6
Store1 B 2
Store2 B 4
Store3 null null
>Solution :
You should CROSS JOIN the Stores and Inv table to get all the possible combinations. Then LEFT JOIN the StoreInv table to get the quantities of each.
SELECT str.StoreId, itm.ItemId, IFNULL(inv.Qty, 0) Qty
FROM Item itm
CROSS JOIN Stores str
LEFT JOIN StoreInv inv ON inv.ItemId = itm.ItemId AND inv.StoreID = str.StoreID