Skip to content

Instantly share code, notes, and snippets.

@adrian-enspired
Last active Oct 30, 2019
Embed
What would you like to do?

tables foo and bar can be related via x or y.

           foo
          ------
          foo_id

    foox          fooy
   ------        ------
   foo_id        foo_id
    x_id          y_id
              
    xbar          ybar
   ------        ------
    x_id          y_id
   bar_id        bar_id
                    
           bar
          ------
          bar_id

so in some cases, we can find the related bar record via x:

select b.bar_id from bar b
  join xbar using (bar_id)
  join foox using (x_id)
  join foo f using (foo_id)
  where f.foo_id = ?

and in other cases, via y:

select b.bar_id from bar b
  join ybar using (bar_id)
  join fooy using (y_id)
  join foo f using (foo_id)
  where f.foo_id = ?

I'm looking for a way to check both possible relationships in a single query, and with only one parameter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment