查詢優化器應該是足夠聰明的最明顯的解決方案有一個可以接受的(接近最佳)性能:
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
on (Id_Object_A, Id_Object_B)
。
兩種方法的實驗;研究查詢計劃以找出最適合您的表格的方式。
這是什麼dbms?所有的對象Id字段都被索引了嗎?您是否查看了執行計劃以確定您的查詢是否已優化? –
它會是sql服務器,是的,每列有一個索引 –