Skip to content

Instantly share code, notes, and snippets.

@adrian-enspired
Last active October 30, 2019 00:54
Show Gist options
  • Save adrian-enspired/2c533b01b2b2a046368642510a262ba5 to your computer and use it in GitHub Desktop.
Save adrian-enspired/2c533b01b2b2a046368642510a262ba5 to your computer and use it in GitHub Desktop.

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