SQL Many To Many Select With Link Table

906 Views Asked by At

I am trying to make my keyword search as efficient as possible using the following 3 tables :

tblImageFiles [ID, ImageURL]

tblTags [ID,Tag]

tblxImagesTags [ID, ImageID, TagID] (this is a linktable joining the above in a many-to-many relationship)

Can anyone help me out with a stored procedure to return ALL images which match ALL search tags entered based on this schema?

Thanks

2

There are 2 best solutions below

7
On BEST ANSWER

The number in the count(distinct aux.TagID) must be equal to the number of tags in where t.Tag in (tag1, tag2, tag3).

select img.* from tblImageFiles img
inner join (
   select it.ImageID from tblTags t
   inner join tblxImagesTags it on it.TagID = t.ID
   where t.Tag in (tag1, tag2, tag3)
   group by it.ImageID
   having count(distinct it.TagID) = 3
) aux on aux.ImageID = img.ID
1
On
        SELECT tblImageFiles.ImageURL
          FROM tblImageFiles
  WHERE EXISTS (SELECT 1
                  FROM tblxImagesTags
            INNER JOIN tblTags
                    ON tblTags.ID = tblxImagesTags.TagID
                 WHERE tblxImagesTags.ImgageID = tblImageFiles.ID
                   AND tblTags.Tag = <searchtag1>)
    AND EXISTS (SELECT 1
                  FROM tblxImagesTags
            INNER JOIN tblTags
                    ON tblTags.ID = tblxImagesTags.TagID
                 WHERE tblxImagesTags.ImgageID = tblImageFiles.ID
                   AND tblTags.Tag = <searchtag2>)
                // etc...

The derived table could be separated out, but the syntax for that depends on what DB you are using. You also need to run a loop to make sure you can cope with a variable number of search terms, but this is the basic idea.