I have a web application that matches images with tags, and I need to create a way to dynamically refine my tag search results. However, I cannot find a clean way to make these SQL queries and that is where I need your help.
The idea is that if I look for the tags "clean" and "dog", I will have image results that have both the tags "clean" and "dog". If I also add the "little" tag, my results would have to narrow down to the images associated with the three tags.
So, with an N-to-N relationship, what is the right way to do this?
My natural approach created code similar to this, but of course I don't like where it goes:
SELECT images.* FROM images INNER JOIN image_tags ON ... INNER JOIN tags ON ... WHERE tags.tag = @tag1 AND EXISTS ( SELECT 1 FROM images INNER JOIN image_tags ON ... INNER JOIN tags ON ... WHERE tag = @tag2 AND EXISTS ( SELECT 1 FROM images INNER JOIN image_tags ON ... INNER JOIN tags ON ... WHERE tag = @tag3 AND EXISTS (...) ... ) )
Of course, this is not very good. Any idea?
Thanks!
sql
Alpha
source share