php - Get undefined join values
I have 3 tables: a shop table, a stock table, and a stock_amounts table. The shop table defines each shop's details, the stock tables defines all stock items, and the stock_amounts table defines how much stock each shop has of an item.
My tables look like this:
*Shop table:
| id | shop
I want to display all the stock that a shop has, but also display the stock that hasn't been defined for that shop. For example, shop 1 has 5 of stock 1, but none of stock 2 or stock 3. I want stock 2 and 3 to display as either zero or NULL value.
I'm currently joining it all together. If I do not specify anything in the{-code-2}
clause, all shops with their stock is shown, and NULL is shown for undefined values. If I do{-code-2} stock_amounts.id <> '2'
, then all NULL values no longer show.
What I want to know:
1) Why does NULL no longer show if I specify 'not 2' in the {-code-2} clause?
2) What is the proper way of doing this, and what would the right MySQL query look like?
Edit:
To be clear, I have no problem whatsoever getting which shop has which stock. The problem I'm having is showing all the stock that shop 1 has + all the stock shop 1 does not have.
My query:{-code-4}
{-code-5}
{-code-6}
This query returns:
{-code-7}
If I add{-code-2} shop <> '2'
, the NULL also disappears. I want a query that will return the following table for shop 1:
{-code-9}
Answer
Answer
Answer
Answer
Answer
Answer
Solution:
You want to use an outer join instead of an inner join. If you provided your query, it would be much easier to tell.
You may be using an outer join. In that case, the condition in the where clause is requiring that
stocks
actually have a match. Remember thatNULL <> 2
evaluates to false, not true.You fix this by putting the condition in the
on
clause.To get the full panoply of shops and stocks, use a driver table that produces all combinations and then join this to the amounts:
If you want to exclude 2, do this in the ss table.
Answer
Solution:
I think that you want to make a left join on
Amounts
with the cross product ofShop
andStock
, which will produce the required null values on stock entries which are non existent for each shop.: