我在表Product_Category(MSSQL 2008 r2)中具有简单的多对多关系:
CREATE TABLE #Product_Category (ProductId int, CategoryId int); go INSERT INTO #Product_Category (ProductId, CategoryId) VALUES (1, 200); go INSERT INTO #Product_Category (ProductId, CategoryId) VALUES (2, 200); go INSERT INTO #Product_Category (ProductId, CategoryId) VALUES (2, 400); go INSERT INTO #Product_Category (ProductId, CategoryId) VALUES (3, 300); go INSERT INTO #Product_Category (ProductId, CategoryId) VALUES (2, 300); go DROP TABLE #Product_Category
如何选择具有以下条件的ProductId:CategoryId = 200 和 CategoryId = 300 且 CategoryId = 400?
查询示例(以下sql不起作用):
SELECT ProductId FROM #Product_Category WHERE CategoryId = ALL (select 200 union select 300 union select 400)
我期望结果:ProductId = 2
select PC.ProductId from #Product_Category as PC where PC.CategoryId in (200, 300, 400) group by PC.ProductId having count(distinct PC.CategoryId) = 3