Wednesday 5 September 2018

Mysql Left Join with conditional on the right table

I'm having trouble figuring out the sql for the following problem of mine. I have two tables like this:

+----------+------------+------------+
| event_id | event_name | event_date |
+----------+------------+------------+

+---------------+----------+---------+--------+
| attendance_id | event_id | user_id | status |
+---------------+----------+---------+--------+

What I am trying to do is to get a table like this:
+----------+--------+
| event_id | status |
+----------+--------+

Where the conditional for the second attendance table is the user_id. I'm trying to get a list of all the events as well as the status of a user for each one of those events, even if there is no record inside attendance (NULL is ok for now). And again, the status data from the attendance table needs to be chosen by the user_id.
From my initial research, I thought this would work:
SELECT event_id, status FROM events LEFT JOIN attendance WHERE attendance.user_id='someoutsideinput' ORDER BY event_date ASC

But that is not working for me as expected..how should I go about this?
Thanks!

all you need to do is to move the condition in the WHERE clause into ON clause.
SELECT events.event_id, COALESCE(attendance.status, 0) status
FROM events LEFT JOIN attendance
     ON events.event_id = attendance.event_id AND
        attendance.user_id='someoutsideinput'
ORDER BY events.event_date ASC

0 comments:

Post a Comment