我有三个看起来像这样的表:
PROD
Prod_ID|Desc ------------ P1|Foo1 P2|Foo2 P3|Foo3 P4|Foo4 ...
内存
Ram_ID|Desc ------------ R1|Bar1 R2|Bar2 R3|Bar3 R4|Bar4 ...
PROD_RAM
Prod_ID|Ram_ID ------------ P1|R1 P2|R2 P3|R1 P3|R2 P3|R3 P4|R3 P5|R1 P5|R2 ...
在PROD和RAM之间,PROD_RAM表描述了多对多关系.
如果Ram_ID设置为(R1,R3),我想找到所有具有给定集合的一个或所有RAM的PROD.
给定(R1,R3)应返回例如P1,P4和P5;不应该返回P3,因为有R1和R3,还有R2.
什么是最快的查询来获得具有给定RAM集的一个或所有Ram_ID的所有PROD?
编辑:
PROD_RAM表可以包含大于1-> 3的关系,因此,对于count = 1 OR = 2的“硬编码”检查不是可行的解决方案.
解决方法
您可以尝试速度的另一种解决方案就是这样
;WITH CANDIDATES AS ( SELECT pr1.Prod_ID,pr2.Ram_ID FROM PROD_RAM pr1 INNER JOIN PROD_RAM pr2 ON pr2.Prod_ID = pr1.Prod_ID WHERE pr1.Ram_ID IN ('R1','R3') ) SELECT * FROM CANDIDATES WHERE CANDIDATES.Prod_ID NOT IN ( SELECT Prod_ID FROM CANDIDATES WHERE Ram_ID NOT IN ('R1','R3') )
或者如果你不喜欢重复设定的条件
;WITH SUBSET (Ram_ID) AS ( SELECT 'R1' UNION ALL SELECT 'R3' ),CANDIDATES AS ( SELECT pr1.Prod_ID,pr2.Ram_ID FROM PROD_RAM pr1 INNER JOIN PROD_RAM pr2 ON pr2.Prod_ID = pr1.Prod_ID INNER JOIN SUBSET s ON s.Ram_ID = pr1.Ram_ID ),EXCLUDES AS ( SELECT Prod_ID FROM CANDIDATES LEFT OUTER JOIN SUBSET s ON s.Ram_ID = CANDIDATES.Ram_ID WHERE s.Ram_ID IS NULL ) SELECT * FROM CANDIDATES LEFT OUTER JOIN EXCLUDES ON EXCLUDES.Prod_ID = CANDIDATES.Prod_ID WHERE EXCLUDES.Prod_ID IS NULL