查询结构与执行

提升 PostgreSQL 查询性能

Amy McCarty

Instructor

子查询与连接

-- SUBQUERY
SELECT COUNT(athlete_id)
FROM athletes
WHERE country IN 
  (SELECT country FROM climate 
    WHERE temp_annual > 22)
-- JOIN
SELECT COUNT(athlete_id)
FROM athletes a
INNER JOIN climate c
  ON a.country = c.country
  AND c.temp_annual > 22
提升 PostgreSQL 查询性能

查询计划

Aggregate  ()
  ->  Hash Join  ()
        Hash Cond: (athletes.country = climate.country)
        ->  Seq Scan on athletes  ()
        ->  Hash  ()
              ->  Seq Scan on climate  ()
                    Filter: (temp_annual > '22'::numeric)
提升 PostgreSQL 查询性能

公用表表达式与临时表

-- CTE
WITH celsius AS 
(
  SELECT country 
  FROM climate 
  WHERE temp_annual > 22 -- Celsius
)
SELECT count(athlete_id)
FROM athletes a
INNER JOIN celsius c
  ON a.country = c.country
-- TEMP TABLE
CREATE TEMPORARY TABLE celsius AS 
  SELECT country 
  FROM climate 
  WHERE temp_annual > 22; -- Celsius

SELECT count(athlete_id)
FROM athletes a
INNER JOIN celsius c
  ON a.country = c.country
提升 PostgreSQL 查询性能

查询计划

  Aggregate  ()
  CTE celsius
    ->  Seq Scan on climate  ()
          Filter: (temp_annual > '22'::numeric)
  ->  Hash Join  ()
        Hash Cond: (a.country_code = c.country_code)
        ->  Seq Scan on athletes a  ()
        ->  Hash  ()
              ->  CTE Scan on celsius c  ()
提升 PostgreSQL 查询性能

限制数据范围

  SELECT country_code
  , COUNT(athlete_id) as athletes
  FROM athletes
  WHERE year in (2014, 2010) -- Indexed column
  GROUP BY country_code
提升 PostgreSQL 查询性能

限制数据范围

  SELECT country_code
  , COUNT(athlete_id) as athletes
  FROM athletes
  WHERE year in (2014, 2010) -- Indexed column
  GROUP BY country_code
无索引 有索引
规划时间:3.370 ms 规划时间:0.163 ms
执行时间:0.143 ms 执行时间:0.062 ms
提升 PostgreSQL 查询性能

聚合——不同粒度

 

SELECT r.country
  , COUNT(a.athlete_id) as athletes
FROM regions r -- country level
INNER JOIN athletes a -- athletes level
  ON r.country = a.country
GROUP BY r.country

 

 

  • 执行时间:0.267 ms
提升 PostgreSQL 查询性能

聚合——改变粒度

WITH olympians AS ( -- country level
  SELECT country
  , COUNT(athlete_id) as athletes
  FROM athletes -- athletes level
  GROUP BY country
)
SELECT country, athletes
FROM regions r -- country level
INNER JOIN olympians o
  ON r.country = o.country
执行时间
先连接 0.267 ms
先聚合 0.192 ms
提升 PostgreSQL 查询性能

Passons à la pratique !

提升 PostgreSQL 查询性能

Preparing Video For Download...