Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to select all records from multiple tables in MySQL even if no match in some tables

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

DEMO

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading