Cải thiện hiệu năng truy vấn trong 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 sẽ dừng tìm trong truy vấn con khi điều kiện là TRUE
IN thu thập toàn bộ kết quả từ truy vấn con trước khi chuyển cho truy vấn ngoài
EXISTS thay cho IN với truy vấn conSELECT 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 |
|---|---|---|
| Nam Á | Ấn Độ | New Delhi |
| Đông Á và Thái Bình Dương | Indonesia | Jakarta |
| Đông Á và Thái Bình Dương | Đông Timor | Dili |
| Châu Phi Sahara | Comoros | Moroni |
| ... | ... | ... |
Ưu điểm
Nhược điểm
Cải thiện hiệu năng truy vấn trong SQL Server