Select distinct document_id from {TABLE} where tag in ('tag1','tag2') group by id having count(tag) >=2
How you generate a list of tags in a where clause depends on the structure of your application. If you dynamically generate a query as part of your code, you can simply build the query as a large, dynamically generated string.
We have always used stored procedures to query data. In this case, we go to the tag list as an XML document. - a similar procedure may look something like one of them, where the input argument will be
<tags> <tag>tag1</tag> <tag>tag2</tag> </tags> CREATE PROCEDURE [dbo].[GetDocumentIdsByTag] @tagList xml AS BEGIN declare @tagCount int select @tagCount = count(distinct *) from @tagList.nodes('tags/tag') R(tags) SELECT DISTINCT documentid FROM {TABLE} JOIN @tagList.nodes('tags/tag') R(tags) ON {TABLE}.tag = tags.value('.','varchar(20)') group by id having count(distict tag) >= @tagCount END
OR
CREATE PROCEDURE [dbo].[GetDocumentIdsByTag] @tagList xml AS BEGIN declare @tagCount int select @tagCount = count(*) from @tagList.nodes('tags/tag') R(tags) SELECT DISTINCT documentid FROM {TABLE} WHERE tag in ( SELECT tags.value('.','varchar(20)') FROM @tagList.nodes('tags/tag') R(tags) } group by id having count( distinct tag) >= @tagCount END
END
source share