使用Postgresql分頁查詢遇到的問題??


1,假設有一個表
結構和索引如下:
create table test1(ID BIGINT,name varchar(10),age int,addr varchar(128));
插入測試數據:
insert into test1 select i,'name'||i,100,substr(md5(random()::text),1,30) from generate_series(1,1000000) as t(i);
-- 創建組合索引,ID + NAME
create index idx_test_id_name on test1(id ,name);
analyze test1;

2,分頁查詢語句
-- sql語句:
select id,name from test1 where id between 1000 and 10000 and name in ('name1','name2','name3')
order by id desc limit 24;

-- 執行計划顯示
explain (analyze,buffers) select id,name from test1 where id between 1000 and 10000 and name in ('name1','name2','name3')
order by id desc limit 24;

Limit (cost=0.42..10879 rows=1 width=51) (actual time=35.174..35.174 rows=0 loops=1)
Buffers:shared hit = 39 read=93
--> Index Scan using idx_test1_id_name on test1(cost=0.42..10879.37 row=1 width=51)(actual time=35.169..35.169 rows=0 loops=1)
Index Cond:((id >=1000 ) and (id <=10000))
Filter:((name)::text = ANY('{name1,name2}'::text[]))
Rows Removed by Filter:9001
Buffers:shared hit=39 read = 93
Planning time : 2.183ms
Execution time : 35.311ms

-- 2個疑問:
第一個問題:
Filter:((name)::text = ANY('{name1,name2}'::text[]))
這步為什么不能在索引的塊中過濾,Pg走的是回表過濾,這樣會造成效率低下。
僅僅是根據idx_test1_id_name的前導列范圍掃描id,直接回表讀取heap page過濾
而且我只選中了id和name兩列都在索引中的,理論上不需要回表嘛,

這點在oracle數據庫中確認沒有回表過程

第二個問題:
postgresql的執行計划很難看出是否真正的回表了。上面的回表過濾我是通過查看 pg_buffercache插件確認的。

請大牛幫忙看看,是否有好的思路和方法。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM