Alright, let's say I have these two tables:
- items with columns id, stuff
- item_properties with columns item_id, prop_id
Now I want to execute a query like
SELECT stuff FROM items WHERE
EXISTS(SELECT * FROM item_properties WHERE prop_id = 123 AND item_id = items.id)
AND EXISTS(SELECT * FROM item_properties WHERE prop_id = 456 AND item_id = items.id)
AND NOT EXISTS(SELECT * FROM item_properties WHERE prop_id = 789 AND item_id = items.id)
AND NOT EXISTS(SELECT * FROM item_properties WHERE prop_id = 101 AND item_id = items.id)
Which works, but looks ugly and is slow. Can anyone think of a smarter way to do this? I can also get the 123,456 and 789,101 lists via a subquery from a third table, if necessary. I am open to suggestions to change my table design as well.
The number of property IDs I need to check the properties of an item against can vary.
Thanks!