因此,我對SQL相當陌生,並且在我目前的實習中負責修改/記錄程序。將SELECT DISTINCT運行到SELECT的優點
要切入,我運行上的表以下查詢:
SELECT COUNT(*) as NumofAccounts
FROM Accounts
WHERE Deleted = 0
AND Account_ID In (SELECT DISTINCT Account_ID FROM Tasks WHERE Deleted = 0);
其產生NumofAccounts = 18
然而原始查詢是的結果:
SELECT COUNT(*) as NumofAccounts
FROM Accounts
WHERE Deleted = 0
AND Account_ID In (SELECT Account_ID FROM Tasks WHERE Deleted = 0);
這兩個查詢都會產生NumofAccounts = 18,但是,如果分隔查詢的這一部分:
SELECT Account_ID FROM Tasks WHERE Deleted = 0;
有736行結果,其中很多都是重複的Account_IDs。
但如果加上DISTINCT:
SELECT DISTINCT Account_ID FROM Tasks WHERE Deleted = 0;
只有18行的結果,這與NumofAccounts嘲弄。
有什麼辦法可以分析這兩個查詢之間的運行時間或效率差異嗎?
對不起,冗長的帖子!
由於'Account_ID'中的內存索引自動創建,'DISTINCT'會執行得更慢。不需要將'DISTINCT'與'IN'語句結合使用。 –
僅供參考,請參閱查詢的估計和實際執行計劃:[(MSDN:execution plans)](https://msdn.microsoft.com/en-us/library/ms189562(v = sql.105) .aspx)這將允許你執行你需要的分析。 –
@ChrisPickford它們在邏輯上是相同的查詢,查詢引擎可能可以解決這個問題併爲它們生成相同的計劃。 – Caleth