Postgres在排序和加入

时间:2016-05-12 15:02:11

标签: sql postgresql sorting indexing database-performance

我有一个父子结构,我正在尝试选择按from_time列排序的那两个表的连接,但Postgres不使用索引,而是对它自己的结果集进行排序。 / p>

我试图猜测背后的原因是什么,因为整个结果集包含75 000行。尝试结果集大到500 000,但最终结果相同。

要概述关系的大小,p_table只包含15行,child_table 75 000。

父表

CREATE TABLE public.p_table (
  id BIGINT PRIMARY KEY NOT NULL,
  from_time TIMESTAMP WITHOUT TIME ZONE NOT NULL,
  to_time TIMESTAMP WITHOUT TIME ZONE NOT NULL
);
CREATE INDEX from_time_idx ON p_table USING BTREE (from_time); 

子表

CREATE TABLE public.child_table (
  id BIGINT PRIMARY KEY NOT NULL,
  p_id BIGINT NOT NULL,
  FOREIGN KEY (p_id) REFERENCES public.p_table (id)
  MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION
);
CREATE INDEX p_id_idx ON child_table USING BTREE (p_id);

我的选择如下:

SELECT
  *
FROM p_table p LEFT OUTER JOIN TRADE child_table t ON p.id = t.p_id
ORDER BY p.from_time ASC;

EXPLAIN的输出表明索引尚未使用。

Sort  (cost=21181.56..21369.06 rows=75000 width=158) (actual time=256.995..275.618 rows=75000 loops=1)
  Output: all columns listed
  Sort Key: p.from_time
  Sort Method: external sort  Disk: 13640kB
  ->  Hash Right Join  (cost=1.34..3313.59 rows=75000 width=158) (actual time=0.829..166.747 rows=75000 loops=1)
        Output: all columns listed
        Hash Cond: (t.p_id = p.id)
        ->  Seq Scan on public.child_table t  (cost=0.00..2281.00 rows=75000 width=134) (actual time=0.493..127.786 rows=75000 loops=1)
              Output: all columns listed
        ->  Hash  (cost=1.15..1.15 rows=15 width=24) (actual time=0.016..0.016 rows=15 loops=1)
              Output: p.id, p.from_time, p.to_time
              Buckets: 1024  Batches: 1  Memory Usage: 1kB
              ->  Seq Scan on public.p_table p  (cost=0.00..1.15 rows=15 width=24) (actual time=0.005..0.007 rows=15 loops=1)
                    Output: p.id, p.from_time, p.to_time
Total runtime: 282.717 ms

0 个答案:

没有答案