SELECT firstname, lastname, id
FROM contact
WHERE id IN
(SELECT contactid
FROM taglist
WHERE contactid IN
(SELECT contactid
FROM customerlist
WHERE companyid = 1) AND (tagid = 1 OR tagid = 4))
I have the query above where there is a single table that has a userid and a tag id. Each user can have multiple tags that are listed as separate entries on this table.
I need to be able to select only users with two or more specified tags. I thought the above query would do this, but it is returning every user with either tag 1 or tag 4.
If I change it to this: (tagid = 1 AND tagid = 4)) I get 0 results because it is only looking at each individual entry, and no entry has more than one tag per user.
This example only has two tags selected, but the goal here is to allow the end user to be able to select any number of available tags and only show results where the user matches all selected tags.
I don't have any way to know a specific number of tags that are going to be selected to match on. Currently there are 20 available tags, and clients can add their own tags if they wish.
So how do I accomplish this? I am very new to SQL queries, and not very familiar with joins yet so I am thinking this is going to have something to do with it, but I don't know. Any nudges in the right direction would be greatly appreciated.
companyid = 1have to do with your queestion?