Outer joins don’t seem to work whether I use a left outer join or right outer join:
SELECT * FROM `event_orchestra_musicians` eom
right outer join `orchestra_instruments` oi on eom.instrument_id = oi.oi_id
where event_id = 2
order by instrument_id
Orchestra_instruments contains different instruments with a unique ID i.e.:
- Violin
- Viola
- Harp
- Piccolo
Event_Orchestra_Musicians is a look up table to join musicians to an instrument i.e.:
musician_id, instrument_id, event_id,
1 1 2
2 1 2
3 3 2
4 2 2
When I do any outer join, using the data in those tables, I would get the results of an inner join (Piccolo wouldn’t show up with a null musician_id, it wont show up at all). Is there something I’m doing wrong?
EDIT:
So I did some monkeying around. The issue seems to be because there is a record in the events_orchestra_musicians table with an event_id of 5 and an instrument_id of 7. If I remove that record, then the outer join works. What I don’t get is if that record is there and I use the where clause to look for event_id = 2, why does it matter if there’s a record in there with an instrument_id of 7 if its event_id is 5?
Try this:
You have to use orchestra_instruments as the base table, since that is the one you want all of the records for, even if no musician exists. I can’t imagine any reasons for using a Right join over a Left join, and Outer is implied. Also, you have to allow event_id to either be 2 or null, because it cannot be 2 if there is no matching record to join.