2013-05-22 214 views
0

我不是那麼高級的sql用戶。 請問您可以查看我的以下查詢是否最優?或者我可以做更多更優化和更可讀的東西?左外連接查詢優化

 select Distinct DT.Station , DT.Slot , DT.SubSlot, DT.CompID , CL.CompName 
      from (
         select Station, Slot, SubSlot, CompID 
         from DeTrace 
         where DeviceID = '1151579773'  
        ) as DT 
      Left outer CList as CL 
        on DT.CompID = CL.CompID 
        where CL.CompName = '9234220' 
        order by CompName 

感謝您的幫助。

回答

2

更容易閱讀這樣的:

select Distinct DT.Station , DT.Slot , DT.SubSlot, DT.CompID , CL.CompName 
      from DeTrace DT  
      Left outer join CList as CL 
        on DT.CompID = CL.CompID 
        where CL.CompName = '9234220' 
        and DT.DeviceID = '1151579773' 
        order by CompName 

優化器應該能夠儘可能有效執行此查詢是你的,但你應該檢查查詢執行計劃只是爲了確保。

0

爲什麼不乾脆:

SELECT DISTINCT DT.Station , DT.Slot , DT.SubSlot, DT.CompID , CL.CompName 
FROM DeTrace DT 
LEFT OUTER JOIN CList CL ON DT.CompID = CL.CompID 
         AND DT.DeviceID = '1151579773' 
         AND CL.CompName = '9234220' 
ORDER BY CL.CompName 
0

我認爲你不需要子查詢。檢查下面:

select Distinct DT.Station , DT.Slot , DT.SubSlot, DT.CompID , CL.CompName    
from DeTrace as DT 
Left outer CList as CL 
on DT.CompID = CL.CompID 
where CL.CompName = '9234220' and DeviceID = '1151579773'  
      order by CompName 
+1

如果在連接中使用WHERE子句,它首先連接所有記錄,然後篩選結果。如果您有加入條件IN,那麼它在加入所有記錄之前首先進行篩選 – Schalk

+0

我同意你的意見。但它可能不會返回預期的輸出,因此在使用外部連接時將搜索謂詞放在where子句中總是可取的,如[顯示](http://nilthakkar.blogspot.in/2011/07/outer-joins-and-search -predicates.html) –

0

我最喜歡的是這樣的:基於

SELECT DISTINCT 
     DeTrace.Station, 
     DeTrace.Slot, 
     DeTrace.SubSlot, 
     DeTrace.CompID, 
     CL.CompName 
    FROM 
     DeTrace 
    LEFT OUTER JOIN 
     CList AS CL ON 
      DeTrace.CompID = CL.CompID 
    WHERE 
     DeviceID = '1151579773' AND 
     CL.CompName = '9234220' 
    ORDER BY 
     CL.CompName 
0
select Distinct DT.Station , DT.Slot , DT.SubSlot, DT.CompID , CL.CompName     
from DeTrace DT 
Left outer join CList as CL 
      on DT.CompID = CL.CompID 
where DT.DeviceID = '1151579773' 
and CL.CompName = '9234220'  
order by CL.CompName 

SQL服務器成本的優化應該能夠確定其適用的條件是最高效的訂單。