改進 SQL Server 中的查詢效能
Dean Smith
Founder, Atamai Analytics
SELECT CustomerID,
CompanyName,
ContactName
FROM Customers c
WHERE EXISTS
(SELECT 1
FROM Orders o
WHERE c.CustomerID = o.CustomerID);
| CustomerID | CompanyName | ContactName |
|---|---|---|
| ALFKI | Alfreds Futterkiste | Maria Anders |
| LAUGB | Laughing Bacchus Wine Cellars | Yoshi Tannamuri |
| QUICK | QUICK-Stop | Horst Kloss |
| ... | ... | ... |
SELECT CustomerID,
CompanyName,
ContactName
FROM Customers
WHERE CustomerID IN
(SELECT CustomerID
FROM Orders);
| CustomerID | CompanyName | ContactName |
|---|---|---|
| ALFKI | Alfreds Futterkiste | Maria Anders |
| LAUGB | Laughing Bacchus Wine Cellars | Yoshi Tannamuri |
| QUICK | QUICK-Stop | Horst Kloss |
| ... | ... | ... |
EXISTS 在條件為 TRUE 時會停止搜尋子查詢
IN 會先收集子查詢的所有結果,再傳給外層查詢
EXISTS 取代 INSELECT CustomerID,
CompanyName,
ContactName
FROM Customers c
WHERE NOT EXISTS
(SELECT 1
FROM Orders o
WHERE c.CustomerID = o.CustomerID);
| CustomerID | CompanyName | ContactName |
|---|---|---|
| FISSA | FISSA Fabrica Inter. Salchichas S.A. | Diego Roel |
| PARIS | Paris spécialités | Marie Bertrand |
SELECT CustomerID,
CompanyName,
ContactName
FROM Customers
WHERE CustomerID NOT IN
(SELECT CustomerID
FROM Orders);
| CustomeID | CompanyName | ContactName |
|---|---|---|
| FISSA | FISSA Fabrica Inter. Salchichas S.A. | Diego Roel |
| PARIS | Paris spécialités | Marie Bertrand |
SELECT UNStatisticalRegion AS UN_Region
,CountryName
,Capital
FROM Nations
WHERE Capital NOT IN
(SELECT NearestPop
FROM Earthquakes);
| UN_Region | CountryName | Capital |
|---|---|---|
SELECT UNStatisticalRegion AS UN_Region
,CountryName
,Capital
FROM Nations
WHERE Capital NOT IN
(SELECT NearestPop
FROM Earthquakes
WHERE NearestPop IS NOT NULL);
| UN_Region | CountryName | Capital |
|---|---|---|
| South Asia | India | New Delhi |
| East Asia and Pacific | Indonesia | Jakarta |
| East Asia and Pacific | East Timor | Dili |
| Sahara Africa | Comoros | Moroni |
| ... | ... | ... |
優點
缺點
NOT IN 對子查詢中 NULL 的處理方式改進 SQL Server 中的查詢效能