6

在我的服务器上运行此查询时,速度很慢,我不明白为什么。谁能帮我弄清楚?
询问:

SELECT
    "t_dat"."t_year" AS "c0",
    "t_dat"."t_month" AS "c1",
    "t_dat"."t_week" AS "c2",
    "t_dat"."t_day" AS "c3",
    "t_purs"."p_id" AS "c4",
    sum("t_purs"."days") AS "m0",
    sum("t_purs"."timecreated") AS "m1"
FROM "t_dat", "t_purs"
WHERE "t_purs"."created" = "t_dat"."t_key"
  AND "t_dat"."t_year" = 2013
  AND "t_dat"."t_month" = 3
  AND "t_dat"."t_week" = 9
  AND "t_dat"."t_day" IN (1,2)
  AND "t_purs"."p_id" IN (
      '4','15','18','19','20','29',
      '31','35','46','56','72','78')
GROUP BY
    "t_dat"."t_year",
    "t_dat"."t_month",
    "t_dat"."t_week",
    "t_dat"."t_day",
    "t_purs"."p_id"

解释分析:

HashAggregate(成本=12252.04..12252.04 行=1 宽度=28)(实际时间=10212.374..10212.384 行=10 循环=1)
  -> 嵌套循环(成本=0.00..12252.03 行=1 宽度=28)(实际时间=3016.006..10212.249 行=14 循环=1)
        加入过滤器:(t_dat.t_key = t_purs.created)
        -> Seq Scan on t_dat (cost=0.00..129.90 rows=1 width=20) (实际时间=0.745..2.040 rows=48 loops=1)
              过滤器: ((t_day = ANY ('{1,2}'::integer[])) AND (t_year = 2013) AND (t_month = 3) AND (t_week = 9))
        -> Seq Scan on t_purs (cost=0.00..12087.49 rows=9900 width=16) (实际时间=0.018..201.630 rows=14014 loops=48)
              过滤器:(p_id = ANY ('{4,15,18,19,20,29,31,35,46,56,72,78}'::integer[]))
总运行时间:10212.470 毫秒
4

3 回答 3

8

很难说你到底错过了什么,但如果我是你,我会确保存在以下索引:

CREATE INDEX t_dat_id_date_idx
    ON t_dat (t_key, t_year, t_month, t_week, t_day);

对于t_purs,创建此索引:

CREATE INDEX t_purs_created_p_id_idx
    ON t_purs (created, p_id);
于 2013-03-03T19:36:29.363 回答
1

考虑在表中使用单列

t_date date

而不是(t_year, t_month, t_week, t_day). 数据类型date占用 4 个字节。这会使你的表缩小一点,使索引更小更快,并且更容易分组。

可以轻松快速地从日期中提取出来extract()。您的查询可能看起来像这样并且会更快:

SELECT extract (year  FROM t_date) AS c0
      ,extract (month FROM t_date) AS c1
      ,extract (week  FROM t_date) AS c2
      ,extract (day   FROM t_date) AS c3
      ,p.p_id                      AS c4
      ,sum(p.days)                 AS m0
      ,sum(p.timecreated)          AS m1
FROM   t_dat  d
JOIN   t_purs p ON p.created = d.t_key
WHERE  d.t_date IN ('2013-03-01'::date, '2013-03-02'::date)
AND    p.p_id IN (4,15,18,19,20,29,31,35,46,56,72,78)
GROUP  BY d.t_date, p.p_id;

对性能更重要的是索引,那么它就是:

CREATE INDEX t_dat_date_idx ON t_dat (t_key, t_date);

或者,根据数据分布:

CREATE INDEX t_dat_date_idx ON t_dat (t_date, t_key);

列的顺序很重要。您甚至可以同时创建两者。

于 2013-03-04T04:30:51.593 回答
1

在此处输入图像描述

t_purs您的查询正在对和进行顺序扫描t_dat。创建适当的索引将帮助您加快查询速度并避免顺序扫描。

create index index_name on t_purs(created) where created is not null;
create index index_name on t_dat using btree(t_key, t_year, t_month, t_week, t_day)

运行上述两个查询后运行解释分析。您会看到计划时间和执行时间将减少。

于 2022-02-06T21:02:53.310 回答