如何优化SQLite3查询

时间:2011-05-06 12:40:35

标签: optimization sqlite

我正在通过一本书(“使用SQLite”)和Northwind数据库学习SQLite3。我编写了以下代码,按照其所在城市的客户数量订购客户,然后按名称按字母顺序排列。

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

运行大约需要50-100毫秒。是否有一个标准程序可以遵循以优化此查询,或者更一般地说,是对其类型的查询?

2 个答案:

答案 0 :(得分:9)

在最常见的情况下,查询优化以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

答案 1 :(得分: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

(为了防止,就像你的情况一样,为同一个值(城市)计算多次计数)