我正在尝试调试 PostgreSQL 9.1.13 数据库上的慢查询,我有点不知所措。ORM 框架生成的确切查询是:
SELECT "core_product"."sales_price", "core_product"."recommended_price", "core_productgroup"."name", "core_product"."number", "core_product"."name", "core_product"."description", "core_product"."cost_price", "core_product"."bar_code", "core_product"."accessible"
FROM "core_product" INNER JOIN "core_productgroup" ON ( "core_product"."product_group_id" = "core_productgroup"."id" )
WHERE "core_productgroup"."company_id" = 1056
ORDER BY "core_product"."id" ASC
LIMIT 200;
Run Code Online (Sandbox Code Playgroud)
此查询需要 28 秒才能返回 200 行,这对于我们的用例来说太慢了。
首次尝试了解性能瓶颈可能在哪里。我首先尝试删除LIMIT 200
预期它会更慢。但是没有LIMIT 200
查询只需要 2 秒就返回大约 293000 行。
如何更快地返回所有 293000 个匹配行而不是仅返回前 200 行?
我尝试使用EXPLAIN
查看两个查询的查询计划有何不同。事实证明,这两个几乎相同的查询具有完全不同的查询计划。与LIMIT
:
QUERY PLAN
----------------------------------------------------------------------------------------------------------------
Limit (cost=10.69..52229.70 rows=200 width=76)
-> Nested Loop (cost=10.69..17054740.55 rows=65320 width=76)
Join Filter: (core_product.product_group_id = core_productgroup.id) …
Run Code Online (Sandbox Code Playgroud) postgresql ×1