简体   繁体   中英

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM