简体   繁体   English

如何优化SQLite3查询

[英]How to optimize an SQLite3 query

I'm learning SQLite3 by means of a book ("Using SQLite") and the Northwind database. 我正在通过一本书(“使用SQLite”)和Northwind数据库学习SQLite3。 I have written the following code to order the customers by the number of customers in their city, then alphabetically by their name. 我编写了以下代码,按照其所在城市的客户数量订购客户,然后按名称按字母顺序排列。

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

It takes about 50-100ms to run. 运行大约需要50-100毫秒。 Is there a standard procedure to follow to optimize this query, or more generally, queries of its type? 是否有一个标准的过程来优化这个查询,或者更一般地说,它的类型的查询?

In the most general case, query optimization starts with reading the query optimizer's execution plan . 在最常见的情况下,查询优化从读取查询优化器的执行计划开始 In SQLite, you just use 在SQLite中,您只需使用

EXPLAIN QUERY PLAN statement

In your case, 在你的情况下,

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

You might also need to read the output of 您可能还需要阅读输出

EXPLAIN statement

which goes into more low-level detail . 进入更低层次的细节

In general (not only SQLite), it's better to do the count for all values (cities) at once, and a join to construct the query: 通常(不仅仅是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

(to prevent, like in your case, the count from being computed many times for the same value (city)) (为了防止,就像你的情况一样,对于相同的值(城市)计算多次计数)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM