Search code examples
mysqlsqlsyntaxsql-match-all

SQL to select half of a two-part composite key based on multiple rows of keys?


I have a table with a composite key like this:

========TABLE========
key_a_col | key_b_col

Scenario:

key_b is 'foo', and there is a 'bar' and 'baz' entry under key_a for it. Another key_b 'fiz' has 'bar' and 'raz'.

Like this:

========TABLE========
key_a_col | key_b_col
    'bar' | 'foo'
    'baz' | 'foo'
    'bar' | 'fiz'
    'raz' | 'fiz'

I want to select all key_b entries where there is both a 'bar' and a 'baz' paired with it in key_a_col. So 'foo' would be returned (bar|foo and baz|foo exist), while 'fiz' would not (only fiz|bar matches).

How can I make this happen?


Solution

  • ypercube's link was perfect. I learned more than a little bit. Anyone reading this in the future should go to:

    How to filter SQL results in a has-many-through relation

    I settled on:

    SELECT distinct(t.b_id)
    FROM   columns_table t
    WHERE  EXISTS (SELECT * FROM columns_table 
                   WHERE  columns_table.id = t.id AND columns_table.col_a = 'bar')
    AND 
    EXISTS (SELECT * FROM columns_table 
                   WHERE  columns_table.id = t.id AND columns_table.col_a = 'baz')
    

    It looks like I can chain WHERE EXISTS clauses an arbitrary number of time and still get good performance. I can also join other tables without making the query complicated to read. If I could upvote ypercube's comment I would.