簡體   English   中英

為什么Postgres沒有在查詢中使用索引

[英]Why postgres is not using the index in my query

我有2張桌子,如下所示:

tb_st:
Columns:
st_id  | integer
st     | character varying(80)
type   | integer
Indexes:
    PRIMARY KEY (st_id)
    UNIQUE INDEX (st, type)
    INDEX (st)

tb_pd:
Column
st_id  | integer
bot_id | integer
Indexes:
    PRIMARY KEY (st_id, bot_id)
    INDEX (bot_id)
Foreign-key constraints:
    FOREIGN KEY (st_id) REFERENCES tb_st(st_id)

當我解釋查詢時:

select p.bot_id
from tb_pd p inner join
     tb_st s
     on p.st_id = s.st_id
where s.st = 'abc' and s.type = 1

postgres給我這個:

 Nested Loop  (cost=4.24..16.10 rows=11 width=194)
   ->  Seq Scan on tb_st s  (cost=0.00..1.07 rows=1 width=186)
         Filter: (((st)::text = 'abc'::text) AND (type = 1))
   ->  Bitmap Heap Scan on tb_pd p  (cost=4.24..14.91 rows=11 width=8)
         Recheck Cond: (st_id = s.st_id)
         ->  Bitmap Index Scan on tb_pd_pkey  (cost=0.00..4.24 rows=11 width=0)
               Index Cond: (st_id = s.st_id)
(7 rows)

過了一會兒給我這個完全相同的查詢(仍然不使用索引):

 Nested Loop  (cost=0.00..2.19 rows=1 width=4)
   Join Filter: (p.st_id = s.st_id)
   ->  Seq Scan on tb_st s  (cost=0.00..1.07 rows=1 width=4)
         Filter: (((st)::text = 'abc'::text) AND (type = 1))
   ->  Seq Scan on tb_pd p  (cost=0.00..1.05 rows=5 width=8)
(5 rows)

我的問題是:如果我僅按構成唯一索引的st值和類型值進行過濾,為什么不使用此唯一索引?

您的表沒有足夠的行來使用索引。 它們適合放在單個磁盤頁面中,因此使用cpu時間讀取整個內容並篩選出行要比兩次執行同​​一操作(一次用於索引,另一次用於數據)更快。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM