I have m:n relationship between users and tags. One user can have m tags, and one tag can belong to n users. Tables look something like this:
USER:
ID
USER_NAME
USER_HAS_TAG:
USER_ID
TAG_ID
TAG:
ID
TAG_NAME
Let’s say that I need to select all users, who have tags “apple”, “orange” AND “banana”. What would be the most effective way to accomplish this using SQL (MySQL DB)?
In addition to the other good answers, it’s also possible to check the condition in a WHERE clause:
The
count(distinct ...)makes sure a tag is counted only once, even if the user has multiple ‘banana’ tags.By the way, the site fruitoverflow.com is not yet registered 🙂