I currently have the following SQL statement:
SELECT s.first_name, s.last_name, tgs.group_identifier
FROM staff s
JOIN staff_training st
ON s.staff_id = st.staff_id
JOIN training_group_staff tgs
ON st.staff_training_id = tgs.staff_training_id
WHERE st.staff_course_id = '164'
training_group_staff only contains the staff_training_id and training_group_id
This statement works as expected and returns all staff names attending course 164 AND have been placed into a group (identified with the group_identifier field).
What I am attempting to do is display all users on training course 164 and if no group selected (there won’t be a row for the specific staff_training_id in training_group_staff) then return null for that column.
Visual Example
Current Statement Returns:
first_name | last_name | group_identifier
Jim | Jones | 3
Harry | Jones | 6
What I am attempting to return is:
first_name | last_name | group_identifier
Jim | Jones | 3
Harriet | Smith | NULL // No row in training_group_staff
Harry | Jones | 6
I have tried several joins, however seem to return the same results – is the desired output possible in one query?
Try with
LEFT JOIN. Should be what you’re after.