查询内的SQL查询集具有完全匹配

时间:2016-02-25 06:22:39

标签: sql

我想根据 EXACT 匹配,根据Attribute_Ids数组选择Product_Id。例如,如果我查询了Attribute_Ids为9,4和2,我希望查询返回Product_Id为1.但是,如果我查询了9和4,我不希望返回任何内容。我该怎么做?

Attribute_Id             |     Product_Id
    9                    |     1
    4                    |     1
    2                    |     1
    9                    |     2
    5                    |     2
    9                    |     3
    6                    |     3
    9                    |     4
    7                    |     4

现在,我可以根据之前的问题返回模糊匹配。你会如何修改它以获得完全匹配? SQL Query Finding a common id in a column based on unique elements in another column

select Product_Id
from table t
where Attribute_Id in (9, 5)
group by Product_Id
having count(*) = 2;

1 个答案:

答案 0 :(得分:2)

试试这个:

SELECT Product_Id
FROM table 
GROUP BY Product_Id
HAVING COUNT(DISTINCT CASE WHEN Attribute_Id IN (9, 5) THEN Attribute_Id END) = 2 AND
       COUNT(CASE WHEN Attribute_Id NOT IN (9, 5) THEN 1 END) = 0

以上查询返回与相关的Product_Id Attribute_Id值9和5 与任何其他{{1}无关}值。

Demo here