Conditional JOINs based on column value
mysql, sql
Solution
SELECT
event.type as type,
IF(type = 'birthday', birthday.id, NULL) as birthday_id,
IF(type = 'graduation', graduation.id, NULL) as graduation_id,
IF(type = 'wedding', wedding.id, NULL) as wedding_id
FROM
event
LEFT OUTER JOIN birthday b ON event.target_id = b.id
LEFT OUTER JOIN graduation g ON b.id IS NULL AND event.target_id = g.id
LEFT OUTER JOIN wedding w ON b.id IS NULL AND g.id IS NULL AND event.target_id = w.id
should do the trick, give me feedback! rgds.
edit: See the IS NULL conditions. I didn't test it, I wonder if mysql would accept it! If yes, then almost only the necessary joins would be done...
Problem
I'm trying to conditionally join one master event table to three others depending on an event type. The select statement works fine, and returns the result set I'd expect, but when I add the JOIN statements, I get an error saying the column aliases were not found: ``` SELECT event.type as type, IF(type = 'birthday', event.target_id, NULL) as birthday_id, IF(type = 'graduation', event.target_id, NULL) as graduation_id, IF(type = 'wedding', event.target_id, NULL) as wedding_id FROM event LEFT OUTER JOIN birthday ON birthday_id = birthday.id LEFT OUTER JOIN graduation ON graduation_id = graduation.id LEFT OUTER JOIN wedding ON wedding_id = wedding.id ``` Gets this error: Unknown column 'birthday_id' in 'on clause' UPDATE: Ok Sebas just indicated you can't join on calculation results, in which case my approach is off. So what is the correct approach for doing something like this?