I working on a tag based search. I have three tables tag(id,name), tagXmedia(id,tag_id,media_id), and media(id,...). tagXmedia is the mapping table between the tag and media tables. This is a one to many relationship.
I could really use a little direction on how to create an "AND" type of search. For instance I need to be able to search for an entry in the media table that is associated with both the "home" and "hawaii" tags.
I have experimented with MySQL exists such as
SELECT
tam.media_id
FROM
tagXmedia tam
LEFT JOIN tag ON tag.id = tam.tag_id
WHERE
EXISTS (SELECT * FROM tag WHERE tag.name = "home")
AND EXISTS (SELECT * FROM tag WHERE tag.name = "hawaii")
Any help on this would really be appreciated.
Try this query:
@kba's answer is correct but you can also do this with a JOIN which is probably more efficient.
I had a similar problem where I wanted to get not just the
media_id
but the actual object and wanted to pass in arbitrary comma separated lists of tags. Here's my complete solution using a stored procedure:Make sure you have this index in tagXmedia:
Here is a test case:
Here is the result:
Note that tag_id 2 and 4 reside in media_id 2 and 5. This is why the query works.
The following should work.
If you wish to have it match more than just two tags, you can easily add them. Just remember to change the 2 in the
HAVING
clause.I assumed all the rows in
tagXmedia
are unique. In case they aren't, you will have to addDISTINCT
to theCOUNT
part.