小编典典

SQL以'= ALL'样式获取行

sql

我在表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


阅读 212

收藏
2021-04-28

共1个答案

小编典典

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
2021-04-28