简体   繁体   中英

Conditional JOIN using field data

I have the following tables:

dog : id, name, event_id which is used to store dogs

event : id, title, owner_id which is used to store events like birthday, vaccines, etc

owner : id, name which is used to store owners. The original owner is a kennel which has an id of 1

owner_event : original_owner_event_id, other_owner_event_id which is used to equate various owner events to each other, ie the original owner might consider a "walk event" equal to the other owner's "play catch" event.


Joining everything:

dog joins event where dog.event_id = event.id

owner joins onto event where event.owner_id = owner.id

Here's the tricky part :

When owner_id > 1 then event joins owner_event where owner_event.other_owner_event_id = event.id

Otherwise, event joins owner_event where owner_event.original_owner_event_id = event.id .


So far I have the following:

SELECT * FROM dog
LEFT JOIN event `event` ON `event`.id = dog.event_id
LEFT JOIN owner `owner` ON `owner`.id = `event`.owner_id
LEFT JOIN owner `owner_event_other` ON `owner_event_other`.other_owner_event_id = `event`.id AND `owner`.id > 1
LEFT JOIN owner `owner_event_original` ON `owner_event_original`.original_owner_event_id = `event`.id AND `owner`.id = 1
WHERE dog.id = 3

I'm just not sure how to actually get the event.title now for dog 3 (for example).

Bearing in mind that it could be the event.id from owner_event.other_owner_event_id column or owner_event.original_owner_event_id column depending on the owner.id .

As only one of the two possibilities can exist for a given owner record, I would suggest to only join owner_event once, but chain event a second time to it in order to retrieve the title via the original owner's event (in case the directly retrieved event record does not represent that title. With COALESCE you can then pick the right title.

SELECT    dog.*,
          COALESCE(original_event.title, event.title) AS original_event_title 
FROM      dog
LEFT JOIN event 
       ON event.id = dog.event_id
LEFT JOIN owner 
       ON owner.id = event.owner_id
LEFT JOIN owner_event
       ON owner_event.other_owner_event_id = event.id
LEFT JOIN event original_event
       ON original_event.id = owner_event.original_owner_event_id
WHERE     dog.id = 3

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