2014-02-21 75 views
1

給定一個表是這樣的:查詢關於同一對象的兩個ID列

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

這是什麼dbms?所有的對象Id字段都被索引了嗎?您是否查看了執行計劃以確定您的查詢是否已優化? –

+0

它會是sql服務器,是的,每列有一個索引 –

回答

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 on (Id_Object_A, Id_Object_B)

兩種方法的實驗;研究查詢計劃以找出最適合您的表格的方式。

相關問題