Jump to content

[SOLVED] Join on empty table


mo

Recommended Posts

I have a query in which I join 3 tables 2 tables have matching data and the third table is currently empty (no rows at all). I want my query to still return results from the successful join even though the 3 table is empty.

 

Tables order_item and store have matching entries and order_fax_status is empty.

SELECT DISTINCT a.`store_id`, a.`store_name`, b.`fax`
FROM `order_item` AS a 
INNER JOIN `store` AS b ON b.`store_id` = a.`store_id`
LEFT JOIN `order_fax_status` AS c ON c.`store_id` = a.`store_id`
WHERE a.`od_id`      = 3
AND   a.`store_id`  <> 1000
AND   c.`fax_status` != 'SUCCESS'

 

If I remove "AND  c.`fax_status` != 'SUCCESS'", the query works.

Link to comment
https://forums.phpfreaks.com/topic/158272-solved-join-on-empty-table/
Share on other sites

You can't check a field from a left joined table if it doesn't match, since it will be NULLed out.  Move this to the ON clause:

 

SELECT DISTINCT a.`store_id`, a.`store_name`, b.`fax`
FROM `order_item` AS a
INNER JOIN `store` AS b ON ( b.`store_id` = a.`store_id` )
LEFT JOIN `order_fax_status` AS c ON (c.`store_id` = a.`store_id` AND   c.`fax_status` != 'SUCCESS' )
WHERE a.`od_id`      = 3
AND   a.`store_id`  <> 1000

 

You can't check a field from a left joined table if it doesn't match, since it will be NULLed out.  Move this to the ON clause:

 

SELECT DISTINCT a.`store_id`, a.`store_name`, b.`fax`
FROM `order_item` AS a
INNER JOIN `store` AS b ON ( b.`store_id` = a.`store_id` )
LEFT JOIN `order_fax_status` AS c ON (c.`store_id` = a.`store_id` AND   c.`fax_status` != 'SUCCESS' )
WHERE a.`od_id`      = 3
AND   a.`store_id`  <> 1000

 

 

Perfect! Works like intended, thanks.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.