我正在通过一本书(“使用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毫秒.是否有一个标准的过程来优化这个查询,或者更一般地说,它的类型的查询?
通常(不仅仅是SQLite),最好一次对所有值(城市)进行计数,并使用连接来构造查询:
SELECT ContactName,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
(为了防止,就像你的情况一样,对于相同的值(城市)计算多次计数)