以不同資料粒度做彙總

改進 PostgreSQL 的查詢效能

Amy McCarty

Instructor

資料粒度-細節層級

 

  • 讓每列唯一
  • 1 個以上欄位

 

Video_Games

id game first_yr
012 Grand Theft Auto 1997
234 Legend of Zelda 1986

 

 

 

Game_Platforms

game_id platform year
234 FCDS 1986
234 GameCube 2003
234 Wii 2006
改進 PostgreSQL 的查詢效能

連接不同粒度

Video_Games 資料表中的 The Legend of Zelda 紀錄,會連到 Games_Platforms 中的 3 筆紀錄。

SELECT g.id, g.game, g.first_yr
  , COUNT(p.platform) AS no_platforms
  , MAX(p.year) AS last_platform_yr
  , p.platform
FROM video_games g
INNER JOIN game_platforms p
  ON g.id = p.game_id
GROUP BY g.id, g.game, g.first_yr
, p.platform
改進 PostgreSQL 的查詢效能

連接不同粒度

 

輸出

id game first_yr no_platforms last_platform_yr platform
234 Legend of Zelda 1986 3 2006 FCDS
234 Legend of Zelda 1986 3 2006 GameCube
234 Legend of Zelda 1986 3 2006 Wii
改進 PostgreSQL 的查詢效能

設定粒度變更

 

Game_Platforms

game_id platform year
234 FCDS 1986
234 GameCube 2003
234 Wii 2006

 

改進 PostgreSQL 的查詢效能

設定粒度變更

SELECT game_id, platform, year
  , COUNT(platform) AS no_platforms
  , MAX(year) AS last_platform_yr
FROM game_platforms
GROUP BY game_id, platform, year

輸出

game_id platform year no_platforms last_platform_yr
234 FCDS 1986 3 2006
234 GameCube 2003 3 2006
234 Wii 2006 3 2006
改進 PostgreSQL 的查詢效能

重溫 CTEs

  • 獨立查詢,含暫存結果集
  • WITH 陳述式
WITH cte AS
  ( SELECT * FROM tableA )

SELECT * FROM cte
  • 允許在連接前先做彙總
改進 PostgreSQL 的查詢效能

CTE 來救援

WITH platforms_cte AS 
(  SELECT game_id, platform, year
      , COUNT(platform) AS no_platforms
      , MAX(year) AS last_platform_yr
   FROM game_platforms
   GROUP BY game_id, platform, year )
SELECT g.id, g.game, cte.no_platforms
  , cte.platform AS last_platform
FROM video_games g
INNER JOIN platforms_cte cte 
  ON g.id = cte.game_id
  AND cte.last_platform_yr = cte.year
改進 PostgreSQL 的查詢效能

CTE 來救援

WITH platforms_cte AS 
(  SELECT game_id, platform, year
      , COUNT(platform) AS no_platforms
      , MAX(year) AS last_platform_yr
   FROM game_platforms
   GROUP BY game_id, platform, year )
SELECT g.id, g.game, cte.no_platforms
  , cte.platform AS last_platform
FROM video_games g
INNER JOIN platforms_cte cte 
  ON g.id = cte.game_id
  AND cte.last_platform_yr = cte.year

輸出

id game no_platforms last_platform
234 Legend of Zelda 3 Wii
改進 PostgreSQL 的查詢效能

連接時對齊資料粒度

 

  • 不重複、不重複值
  • 僅取必要結果
  • 避免重複計數
改進 PostgreSQL 的查詢效能

一起來練習吧!

改進 PostgreSQL 的查詢效能

Preparing Video For Download...