我有主题(id*)和标签(id*,name)和链接表topic_tags(topicFk*,tagFk*).
现在我想选择每个主题,它包含所有好的标签(a,b,c),但没有坏标签(d,e,f).
我怎么做?
假设您的Topic_Tags表是唯一的,这可以回答您的确切问题 - 但可能无法推断您的实际问题:
SELECT TopicId FROM Topic_Tags JOIN Tags ON Topic_Tags.TagId = Tags.TagId WHERE Tags.Name IN ('A', 'B', 'C', 'D', 'E', 'F') GROUP BY TopicId HAVING COUNT(*) = 3 AND MAX(Tags.Name) = 'C'
更通用的解决方案是:
SELECT * FROM ( SELECT TopicId FROM Topic_Tags JOIN Tags ON Topic_Tags.TagId = Tags.TagId WHERE Tags.Name IN ('A', 'B', 'C') GROUP BY TopicId HAVING COUNT(*) = 3 ) as GoodTags LEFT JOIN ( SELECT TopicId FROM Topic_Tags JOIN Tags ON Topic_Tags.TagId = Tags.TagId WHERE Tags.Name = 'D' OR Tags.Name = 'E' OR Tags.Name = 'F' ) as BadTags ON GoodTags.TopicId = BadTags.TopicId WHERE BadTags.TopicId IS NULL