Apologies for the hand-wavy title, I honestly couldn't come up with a better description while keeping the text short. Here's the full problem.
In a table with two columns, I'd like to select the one entry in the first column that has all the values I specify in the second column. This is better explained with a toy example (also on SQL Fiddle).
Suppose I have a table like this:
CREATE TABLE t (fruit TEXT, color TEXT);
INSERT INTO t (fruit, color) VALUES
('banana', 'green'),
('banana', 'yellow'),
('apple', 'green'),
('apple', 'red'),
('apple', 'yellow'),
('strawberry', 'green'),
('strawberry', 'red');
Given a number of colors, I'd need to retrieve the fruit (you can assume there will be only one) that has all those colors - not more, not less.
So if I query for "green and red" I should get "strawberry". However, if I query for "green and yellow" I should see "banana" and not "apple" because the latter also has an additional color.
So far what I've come up with is a horrible hack using INTERSECT
:
WITH cte AS (
SELECT fruit FROM t WHERE color = 'green'
INTERSECT SELECT fruit FROM t WHERE color = 'yellow')
SELECT fruit FROM cte;
which of course fails, because returns both banana and apple.
Anyone has a better plan?