MYSQL Left Join with Conditional OR

Ok, I'm semi-efficient with SQL and I tried using the OR operator on the left join and found it didn't work.

The reason for this is because I have two columns from two tables that I am trying to use to join if one returns NULL. I have two tables - events and seasons. Each table has a sponsor id column that I use to join the sponsors table. The reason for this is that sometimes one event is sponsored rather than the entire season or vice versa.

My question is how best I can do this. My original query is not like 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 use OR se.season_sponsor=sp.sponsor_id

Ultimately, I am trying to join the sponsors table using ev.event_sponsor or se.season_sponsor. Any help is much appreciated. I did a bit of research and couldn't find an answer to what I was trying to accomplish.

+3


source to share


1 answer


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

      

+1


source







All Articles