postgresql - Postgres解释计划对于具有不同参数的相同查询是不同的
问题描述
当我使用不同的参数值vsexplain
运行以下查询时,我不知道为什么查询会产生不同的结果:sender_id = 2015
sender_id = 2016
- 与
sender_id = 2015
:
EXPLAIN SELECT
*
FROM
shipment.shipments shipment0_
WHERE
(shipment0_.status IN (0 ,1 ,2))
AND shipment0_.sender_id = 2015
ORDER by shipment0_.id DESC
LIMIT 10;
Limit (cost=0.43..4.92 rows=10 width=11006)
-> Index Scan Backward using shipments__id_pk on shipments shipment0_ (cost=0.43..446315.18 rows=993372 width=11006)
Filter: ((sender_id = 2015) AND (status = ANY ('{0,1,2}'::bigint[])))
- 与
sender_id = 2016
:
EXPLAIN SELECT
*
FROM
shipment.shipments shipment0_
WHERE
(shipment0_.status IN (0 ,1 ,2))
AND shipment0_.sender_id = 2016
ORDER by shipment0_.id DESC
LIMIT 10;
Limit (cost=0.43..16.33 rows=10 width=11006)
-> Index Scan using idx_sender_id_id on shipments shipment0_ (cost=0.43..155621.11 rows=97858 width=11006)
Index Cond: (sender_id = 2016)
Filter: (status = ANY ('{0,1,2}'::bigint[]))
在shipment.shipments
表中有 1M 记录sender_id = 2015
:
select count(*) from shipment.shipments where sender_id = 2015; -- 1000000 records
select count(*) from shipment.shipments where sender_id = 2016; -- 90000 records
以下是表格的 DDL shipment.shipments
:
CREATE TABLE shipment.shipments (
id bigserial NOT NULL,
shp_date varchar(50) NULL,
shp_time varchar(50) NULL,
sender_id int8 NULL,
status int8 NULL,
pickup_order_id int8 NULL,
CONSTRAINT shipments__id_pk PRIMARY KEY (id),
CONSTRAINT shipments__pickup_orders_id_fk FOREIGN KEY (pickup_order_id) REFERENCES shipment.pickup_orders(id)
);
CREATE INDEX idx_sender_id_id ON shipment.shipments USING btree (sender_id, id DESC);
CREATE INDEX shipments__sender_id_idx ON shipment.shipments USING btree (sender_id);
查询sender_id = 2016
运行速度非常快,order by limit
但sender_id = 2015
速度非常慢并且不使用 index idx_sender_id_id
。你能帮我解释一下吗?以及如何提高查询速度sender_id = 2015
。太感谢了!
解决方案
推荐阅读
- shopify - 如何在 shopify 中应用标签过滤和价格过滤
- python - TensorFlow 非常高的损失值
- django - 如何将分页器添加到 django 代码中?
- python - input() 函数需要在 ctrl-c 之后使用自定义信号处理函数输入
- python-3.x - Pyinstaller exe在启动时不起作用
- sql - 这些查询中的哪一个更有效和更高效地从列中细化 Max Value
- javascript - 调用 in_app.js 的函数不会总是在某些时候加载 next.js
- linux - 货物错误:无法为“atk-sys v0.10.0”运行自定义构建命令
- python - 我用 for 循环写了这个等式。有人知道写这个方程的其他形式吗?
- google-calendar-api - 增量同步忽略原始过滤器