I have the following SQL:
SELECT *
FROM [Database].dbo.[TagsPerItem]
INNER JOIN [Database].dbo.[Tag] ON [Tag].Id = [TagsPerItem].TagId
WHERE [Tag].Name IN ('home', 'car')
and it returns:
Id TagId ItemId ItemTable Id Name SiteId
------------------------------------------
1 1 1 Content 1 home 1
2 1 2 Content 1 home 1
3 1 3 Content 1 home 1
4 2 4 Content 2 car 1
5 2 5 Content 2 car 1
6 2 12 Content 2 car 1
instead of just two records, which these names are “home” and “car”. How can I fix it?
Thanks.
There are two alternatives – using JOINs:
…or
HAVING COUNT(DISTINCT t.name) = 2:COUNT(DISTINCTis necessary, otherwise two relations of “car” would be a false positive (assuming possible in the data model)COUNT(DISTINCT...); while tedious to construct, JOINing to the same table multiple times is a safer method