给出一个这样的表:
Id_Table | Id_Object_A | Id_Object_B
并且给出了ID_Object的两个子集,我必须检查这个条件:
(ID_Object_A IN (1,2,3,4,5) AND ID_Object_B IN (6,7,8,9,10))
OR
(ID_Object_A IN (6,7,8,9,10) AND ID_Object_B IN (1,2,3,4,5))
在表现方面,最好的方法是什么?
答案 0 :(得分:1)
查询优化器应足够智能,以便最明显的解决方案具有可接受(接近最佳)的性能:
SELECT *
FROM MyTable
WHERE (ID_Object_A IN (1,2,3,4,5) AND ID_Object_B IN (6,7,8,9,10))
OR (ID_Object_A IN (6,7,8,9,10) AND ID_Object_B IN (1,2,3,4,5))
但SQL Server的真正优势在于优化JOIN
。生成一个包含10个数字的所有50种可能组合的表格:
CREATE TABLE ReferencesAB (a int NOT NULL, b int NOT NULL)
CREATE NONCLUSTERED INDEX Covering ON ReferencesAB (a, b)
INSERT INTO ReferencesAB
SELECT *
FROM (VALUES (1), (2), (3), (4), (5)) AS values1 (a)
CROSS JOIN (VALUES (6), (7), (8), (9), (10)) AS values2 (b)
INSERT INTO ReferencesAB
SELECT *
FROM (VALUES (6), (7), (8), (9), (10)) AS values1 (a)
CROSS JOIN (VALUES (1), (2), (3), (4), (5)) AS values2 (b)
然后将您的表连接到参考表:
SELECT *
FROM MyTable t
INNER JOIN ReferencesAB r ON r.a = Id_Object_A AND r.b = Id_Object_B
为了做得好,我认为最好在MyTable
上对(Id_Object_A, Id_Object_B)
编制索引。
尝试两种方法;研究查询计划,找出哪种方法最适合你的桌子。