Thursday, 30 August 2018

LEFT / RIGHT JOIN does not return empty row

I have a query which uses a self join on 2 tables to return a single row of results. The problem I have is that if seat1 is empty, I don't get anything returned.

SELECT seat1.seat_type_id
     , seat1.seat_type_qty
     , seat2.seat_type_id
     , seat2.seat_type_qty
  FROM jos_sv_apptpro2_requests AS R
  LEFT JOIN jos_sv_apptpro2_seat_counts AS seat1 ON R.id_requests = seat1.request_id
  LEFT JOIN jos_sv_apptpro2_seat_counts AS seat2 ON R.id_requests = seat2.request_id
 WHERE (seat1.seat_type_id = 6 AND seat2.seat_type_id = 7)
   AND R.id_requests = 8703
   AND R.resource = 3

This should return:
seat_type_id 6
seat_type_qty 0 <= this is the empty row
seat_type_id1 7
seat_type_qty 1

EDIT: I've now got:
SELECT
IFNULL(seat1.seat_type_qty,0) AS seat_type_qty,
IFNULL(seat2.seat_type_qty,0) AS seat_type_qty
FROM jos_sv_apptpro2_requests AS R
LEFT JOIN jos_sv_apptpro2_seat_counts AS seat1
ON R.id_requests = seat1.request_id AND seat1.seat_type_id = 6
LEFT JOIN jos_sv_apptpro2_seat_counts AS seat2
ON R.id_requests = seat2.request_id AND seat2.seat_type_id = 7
WHERE R.id_requests = 8696

REEDIT! - My mistake, I'm returning seat_type_qty twice as an object in my PHP. All sorted now - THANKS!

WHERE seat1.seat_type_id = 6 AND seat2.seat_type_id = 7

is what removes all rows with NULL values. You should move those condition to the JOIN criteria so that the RDBMS does what you are expecting:
LEFT JOIN jos_sv_apptpro2_seat_counts AS seat1 ON R.id_requests = seat1.request_id
                                              AND seat1.seat_type_id = 6
LEFT JOIN jos_sv_apptpro2_seat_counts AS seat2 ON R.id_requests = seat2.request_id
                                              AND seat2.seat_type_id = 7

0 comments:

Post a Comment