2011-05-06 90 views
5

我正在通過一本書(「使用SQLite」)和Northwind數據庫來學習SQLite3。我寫了下面的代碼,通過他們城市中的客戶數量,然後按照他們的名字按字母順序排列客戶。如何優化SQLite3查詢

SELECT ContactName, Phone, City as originalCity 
FROM Customers 
ORDER BY (
     SELECT count(*) 
     FROM Customers 
     WHERE city=originalCity) 
    DESC, ContactName ASC 

運行大約需要50-100ms。有沒有一個標準的過程來優化這個查詢,或更一般地說,它的類型的查詢?

回答

1

總體(不僅是SQLite的),最好是做一次所有的值(城市)的數量,並且加入構造查詢:

SELECT ContactName, Phone, Customers.City as originalCity 
     FROM Customers 
     JOIN (SELECT city, count(*) cnt 
       FROM Customers 
      GROUP BY city) Customers_City_Count 
     ON Customers.city = Customers_City_Count.city 
    ORDER BY Customers_City_Count.cnt DESC, ContactName ASC 

(預防,像你的情況,對同一個值(城市)多次計算的次數)

7

在最一般情況下,查詢優化以reading the query optimizer's execution plan開頭。 SQLite中,你只需要使用

EXPLAIN QUERY PLAN statement 

在你的情況,

EXPLAIN QUERY PLAN 
SELECT ContactName, Phone, City as originalCity 
FROM Customers 
ORDER BY (
     SELECT count(*) 
     FROM Customers 
     WHERE city=originalCity) 
    DESC, ContactName ASC 

您可能還需要閱讀的

EXPLAIN statement 

,其輸出進入more low-level detail