I store some data in MySQL and want to filter out rows that match a given criteria.
Sounds easy, but it is not since there are some join criteria involved.
I do have the following tables:
items : id, ...
genres: id, name:varchar, item_id
Each item has multiple genres.
The query should filter out items if at least one genre does match a given genre name (or a set of names).
For example:
Item with id 1 has 3 genres
- genre name = 'foo'
- genre name = 'bar'
- genre name = 'baz'
Item 1 may not be part of the result set if the given genre name is ‘bar’, [‘bar’, ‘baz’, ‘xyz’], etc.
I tried to left join the genres on the items and applied a WHERE statement with “genres.name NOT IN (?)”. ? is the given set of genre names.
This (of course) only works for items with exactly one genre. The same could be achieved by multiple WHERE conditions: WHERE name <> ‘a’ AND name <> ‘b’ …
Any ideas how to get this query done properly?
Thanks in advance!
You can use a correlated subquery.
Example:
A correlated subquery differs from other subqueries in that it references the outer query.
Correlated subqueries are run for each row projected/selected by the outer query.