MySQL: LEFT JOIN.. select all from table 1 even if not there in table 2?
I am joining a few tables for a selection
If there isnt anything matching in the 2nd, 3rd, 4th tables I still want to pull the results as long as the first table has a match. I thought LEFT JOIN did this, but it is not.
Here is the full query:
SELECT cart_product.*, prod_drop_products.prod_drop_product_name, everlon_sheet.*, cart_product.product_id AS product_id
FROM cart_product
LEFT JOIN everlon_sheet ON cart_product.product_id = everlon_sheet.product_id
LEFT JOIN prod_drop_products ON cart_product.product_id = prod_drop_products.product_id
LEFT JOIN prod_drop ON prod_drop.prod_drop_id = prod_drop_products.prod_drop_id
WHERE prod_drop.prod_drop_name = "Carat Weight" AND cart_product.product_brand = "everlon"
ORDER BY cart_product.product_manufacturer_num
which pulls 316 results
Here is the 开发者_如何学编程query without the joins:
SELECT cart_product.*
FROM cart_product
WHERE cart_product.product_brand = "everlon"
ORDER BY cart_product.product_manufacturer_num
which pulls 362 results
I have a hunch this is happening because of my WHERE prod_drop.prod_drop_name = "Carat Weight" clause in the JOIN qry. But is there a way to pull what I need in my query above but still pull everything from the first (most left, cart_product) table even if nothing matches in the other tables?
Thanks!!
If there is no match on the right side prod_drop.prod_drop_name will be null
Adding OR prod_drop.prod_drop_name IS NULL should fix your problem.
try
WHERE prod_drop.prod_drop_name = "Carat Weight" or prod_drop.prod_drop_name is null
Change
WHERE prod_drop.prod_drop_name = "Carat Weight" AND cart_product.product_brand = "everlon"
to
WHERE (prod_drop.prod_drop_name = "Carat Weight" OR prod_drop.prod_drop_name IS NULL) AND cart_product.product_brand = "everlon"
The query will now also return a match if there is no matching value in prod_drop.
精彩评论