Tyler
Tyler

Reputation: 69

MYSQL Left Join with conditional OR

Ok, I am semi efficient with SQL and I tried using an OR statement in a left join and found it didn't work.

The reason for me doing this is because I have two columns from two tables that I am trying to use to join if one returns NULL. I have a two tables - events and seasons. Each table has a sponsor id column which I use to join the sponsors table. The reason behind this is because sometimes a single event is sponsored rather than the whole season or the other way around.

My question is whats the best way I can do this. My original query isn't the same as this but its the same concept (except it doesn't grab every column from every table).

SELECT sp.*, re.*, ev.*, se.* 
FROM events ev 
INNER JOIN seasons se ON se.season_id=ev.event_sid 
INNER JOIN results re ON ev.event_id=re.results_eid 
LEFT JOIN sponsors sp ON ev.event_sponsor=sp.sponsor_id

and at the end I tried to tack on OR se.season_sponsor=sp.sponsor_id

Ultimately I am trying to join the sponsors table with either ev.event_sponsor or se.season_sponsor. Any help is much appreciated. I did a little researching and couldn't find an answer to what I was trying to accomplish.

Upvotes: 3

Views: 83

Answers (1)

user359040
user359040

Reputation:

Try:

SELECT sp.*, re.*, ev.*, se.* 
FROM events ev 
INNER JOIN seasons se ON se.season_id=ev.event_sid 
INNER JOIN results re ON ev.event_id=re.results_eid 
LEFT JOIN sponsors sp ON COALESCE(ev.event_sponsor,se.season_sponsor)=sp.sponsor_id

Upvotes: 1

Related Questions