我需要運行查詢來比較兩個表並返回不在第二個表中的記錄。棘手的部分是兩個表之間的鏈接是有條件的。我有多個數據源輸入表2,然後輸入表1。我試過使用一個連接,但是這並不比我下面提到的要快。這些表格中有大約5萬條記錄。該查詢大約需要1.5分鐘才能完成。我希望能把它弄到幾秒鐘。表1和表2已經在這些字段上有索引。數據庫在兼容級別SQL2008上運行。使用條件連接優化SQL查詢
此查詢時間約1.5分鐘:
select *
from Table1 t1
where not exists (select *
from Table2 t2
where t2.seedID = case t2.SeedSource when 'SeedSource1' then t1.SeedSource1
when 'SeedSource2' then t1.SeedSource2
when 'SeedSource3' then t1.SeedSource3
when 'SeedSource4' then t1.SeedSource4
when 'SeedSource5' then t1.SeedSource5 end)
此查詢需要5分鐘以上:
select d.*
from Tabel1 t1 left join
Table2 t2 on t2.seedID = case t2.SeedSource when 'SeedSource1' then t1.SeedSource1
when 'SeedSource2' then t1.SeedSource2
when 'SeedSource3' then t1.SeedSource3
when 'SeedSource4' then t1.SeedSource4
when 'SeedSource5' then t1.SeedSource5 end
where t2.seedID is NULL
任何幫助將不勝感激。
左右,這表是'M'和表是'd',他們怎麼知道't1'和't2'? – SqlZim
您能否包含與問題相關的表結構的子集? –
你有太多的別名來確定你正在嘗試完成什麼d,t1,t2,m –