Ora*_*oap 6 sqlite optimization
我正在通过一本书("使用SQLite")和Northwind数据库学习SQLite3.我编写了以下代码,按照其所在城市的客户数量订购客户,然后按名称按字母顺序排列.
SELECT ContactName, Phone, City as originalCity
FROM Customers
ORDER BY (
SELECT count(*)
FROM Customers
WHERE city=originalCity)
DESC, ContactName ASC
Run Code Online (Sandbox Code Playgroud)
运行大约需要50-100毫秒.是否有一个标准的过程来优化这个查询,或者更一般地说,它的类型的查询?
在最常见的情况下,查询优化从读取查询优化器的执行计划开始.在SQLite中,您只需使用
EXPLAIN QUERY PLAN statement
Run Code Online (Sandbox Code Playgroud)
在你的情况下,
EXPLAIN QUERY PLAN
SELECT ContactName, Phone, City as originalCity
FROM Customers
ORDER BY (
SELECT count(*)
FROM Customers
WHERE city=originalCity)
DESC, ContactName ASC
Run Code Online (Sandbox Code Playgroud)
您可能还需要阅读输出
EXPLAIN statement
Run Code Online (Sandbox Code Playgroud)
进入更低层次的细节.
一般来说(不仅是 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
Run Code Online (Sandbox Code Playgroud)
(为了防止像您的情况一样,对同一值(城市)多次计算计数)