I’m a SQL novice, trying to understand how to do a slightly complicated query. Working in a Rails 3 app, I have a many-to-many relationship between Photos and Terms. The setup is pretty vanilla:
photos: id
terms: id
photos_terms: photo_id | term_id
What I’d like to be able to do is find AND and OR matches among any arbitrary group of terms. So for instance, in pseudo SQL:
Select Photos where Term ID in (1 or 2) and (3 or 4 or 5) and (6).
How can you write a query like that? For reference, I’m using PostgreSQL.
Update In response to Rubens answer, here’s a bit more info that may help explain the grouping, though I wasn’t sure if it was relevant before:
There is another model, Taxonomy, so taxonomies table. Each term belongs to a Taxonomy, and a Taxonomy can be either inclusive (meaning it is possible for multiple terms from that taxonomy to apply) or exclusive (meaning terms in that taxonomy are mutually exclusive, only one could apply).
The table relationship is like this:
terms: id | taxonomy_id
taxonomy: id | inclusive(boolean)
The grouping would be terms from different taxonomies, you always want an AND match for each grouping. You want an AND match among terms from an inclusive Taxonomy, and you want an OR match among terms from an exclusive taxonomy.
To give another pseudo-code example, if we had the following:
Taxonomy: Color (inclusive = true)
Terms: Red, Blue, Green
Taxonomy: Location (inclusive = false)
Terms: NY, NJ, PA, MD
I might want to query like this:
Photos where terms in (red and blue) and (NY or NJ).
Does that make sense? FWIW the terms are just like highly structured tags.
1 Answer