Question

I have a query with some LEFT JOIN's. I am trying to make one of them show the NULL matches when one clause is not matched.

SELECT *, sr.id as role_id, ss.id as scheduled_entry_id
FROM T_STAFF_ROLE AS sr
LEFT JOIN T_STAFF_SCHEDULE AS ss
ON sr.id = ss.staff_role_id
LEFT JOIN T_BOOKINGS_ADMIN AS ba
ON ba.id = ss.admin_user_id
AND ss.client_booking_id='12495' // unreal id
ORDER BY sr.id 

I would like to always show the T_STAFF_ROLE entries.
If there is a match here ss.client_booking_id=".$id_booking.' show that, otherwise return the field with NULL values.

I tried with AND (as it is now), but then I get all results with other ss.client_booking_id also.

Tried with WHERE but then I don'r get anything if there is no match. I would like to still get one entry per row on sr. I thought that was the point with the "LEFT" JOIN

Where is my logic or code wrong?

My rendered query:

SELECT *, sr.id as role_id, ss.id as scheduled_entry_id 
FROM staff_role AS sr 
LEFT JOIN staff_schedule AS ss ON sr.id = ss.staff_role_id 
LEFT JOIN admin_users AS ba ON ba.id = ss.admin_user_id 
AND ss.client_booking_id=336 ORDER BY sr.id

My sr has 9 rows, it's fixed. Different roles like taxi, cleaner, tourist guide. The ss is bookings of a certain role/person. I use this query on PHP to generate HTML, and would like it to generate data for all the "roles" in case some of them is not matched.

Was it helpful?

Solution

The condition AND ss.client_booking_id=".$id_booking.' is in the wrong place. It should be part of the join with T_STAFF_SCHEDULE. In your current query, you get all T_STAFF_SCHEDULE that match sr.id, and all T_BOOKINGS_ADMIN when any of its parent T_STAFF_SCHEDULE matches $id_booking.

Well, I don't know the meaning of every column and table, but I think it should look like this:

 "SELECT *, sr.id as role_id, ss.id as scheduled_entry_id
    FROM ".T_STAFF_ROLE." AS sr
    LEFT JOIN ".T_STAFF_SCHEDULE." AS ss
    ON sr.id = ss.staff_role_id
    AND ss.client_booking_id=".$id_booking."
    LEFT JOIN ".T_BOOKINGS_ADMIN." AS ba
    ON ba.id = ss.admin_user_id
    ORDER BY sr.id"; 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top