phouse512
phouse512

Reputation: 680

Left Join with conditional on 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!

Upvotes: 1

Views: 1710

Answers (2)

John Woo
John Woo

Reputation: 263683

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

Upvotes: 6

Declan_K
Declan_K

Reputation: 6826

You need to more that condition to the JOIN clause instead of the WHERE clause.

BTW, you have not specified the join criteria between the tables, I have also corrected that below.

SELECT E.event_id
        ,A.status 
FROM    events E
LEFT JOIN 
        attendance A
ON      E.event_id = A.event_id
AND     A.user_id='someoutsideinput' 
ORDER BY 
        E.event_date ASC

Upvotes: 1

Related Questions