2017-02-23 43 views
1

我有2個表假設TABLE_1 & TABLE_2 TABLE_1有56列和120萬條記錄 我的查詢像SQL NOT IN查詢花費的時間與類似的表

TABLE_1像

RollNumber | Subject | G   | Part | Status 
------------------------------------------------ 
1   | 1  | 1   | 1 | 1 
1   | 1  | 1   | 2 | 1 
1   | 2  | 1   | 1 | 1 
1   | 2  | 1   | 2 | 5 
1   | 3  | 1   | 1 | 0 
1   | 3  | 1   | 2 | 1 
2   | 1  | 2   | 1 | 1 
2   | 1  | 2   | 2 | 1 
2   | 2  | 2   | 1 | 1 
2   | 2  | 2   | 2 | 1 
2   | 3  | 2   | 1 | 1 
2   | 3  | 2   | 2 | 1 
3   | 1  | 2   | 1 | 1 
3   | 1  | 2   | 2 | 1 
3   | 2  | 2   | 1 | 1 
3   | 2  | 2   | 2 | 1 
3   | 3  | 2   | 1 | 0 
3   | 3  | 2   | 2 | 1 

我想來自table_1的所有RollNumber(由第2列和第3列組成),其中任何狀態爲0但不希望同時具有狀態= 5(或不等於1)的學生

我試過

select * from table_1 as t1 
inner join table_2 as t2 
on t1.column2 = t2.column2 and t1.column3 = t2.column3 and t1.column4 = t2.column4 
where t1.column1 not in 
    (select column1 from table_1 where status = 5) 

這是我qhole查詢的最內部查詢
我也曾嘗試EXCEPT條款
兩個查詢需要很長時間才能執行

+0

爲什麼使用子查詢來過濾'status'? –

+1

請顯示查詢的[執行計劃](http://stackoverflow.com/questions/7359702/how-do-i-obtain-a-query-execution-plan)。你有索引添加到'column1','column2','column3'和'status'嗎? – kennytm

+0

@kennytm我已編輯的問題,請現在審查,,,謝謝 – Brainiac

回答

1

可以代替NOT IN.這將使用EXISTS比較快,因爲會有boolean比較,而不是string比較。

select * from table_1 as t1 
inner join table_2 as t2 
on t1.column1 = t2.column1 and t1.column2 = t2.column2 and t1.column3 = t2.column3 
where not EXISTS 
    (select 1 from table_1 where status = 5 and t1.column3 = table_1.column3) 
1

嘗試使用NOT EXISTS代替NOT IN

SELECT * 
FROM table_1 AS t1 
INNER JOIN table_2 AS t2 
ON t1.column1 = t2.column1 AND t1.column2 = t2.column2 AND t1.column3 = t2.column3 
WHERE NOT EXISTS(
        SELECT 1 
        FROM table_1 
        WHERE status=5 AND column3=t1.column3 
                  ) 
1

與SQL Server 2008開始,您可以使用count() over()計算在給定組總多行如何有一定的價值。

在這種情況下,您需要計算每組status <> 1的數量,並且只選擇屬於組數爲0的組的行。

select * from (
    select * , 
     count(case when status <> 1 then 1 end) over(partition by RollNumber, G) c 
    from table_1 
) t where c = 0 
+0

這是工作,,,但問題是我必須在C#中轉換爲LINQ,謝謝你的方式 – Brainiac

+0

如果你需要幫助轉換查詢到LINQ,我建議打開一個新的問題:) – FuzzyTree

+0

我想這個查詢還爲MySQL – Brainiac