我在写一个棘手的问题时遇到了问题。我有下表(作为例子)
fusionId | productId | departmentId
1 | 1 | 1
2 | 1 | 2
3 | 2 | 1
4 | 3 | 2
我想要一个查询,我可以将两个departmentId
传递给(1,2),并且只有当productId
与departmentId
匹配时才会返回productId
departmentId
1}}
例如,如果我发送了productId
1
的1& 2我会得到结果
{{1}}
这可能吗?
答案 0 :(得分:11)
SELECT productId
FROM YourTable
WHERE departmentId IN (1,2)
GROUP BY productId
HAVING COUNT(DISTINCT departmentId) = 2
或者
SELECT productId
FROM YourTable
WHERE departmentId = 1
INTERSECT
SELECT productId
FROM YourTable
WHERE departmentId = 2
答案 1 :(得分:0)
Create Table Temporary
(
fusionId int,
productId int,
departmentId int,
)
insert into Temporary values (1,1,1),(2,1,2),(3,2,1),(4,3,2)
Select productId from Temporary
Where productId in (Select productId from Temporary where departmentId = 1) and departmentId =2
答案 2 :(得分:0)
SELECT productId
FROM YourTable
WHERE departmentId IN (1,2)
GROUP bY productId
HAVING COUNT(productId) > 1