美好的一天,我的问题是关于优化SQL查询。 以下查询很慢:
SELECT id, name,
, (SELECT rank_time FROM stage_rank WHERE stage = stage.id ORDER BY rank_time DESC LIMIT 1)::date AS rank_time
, (SELECT host_c FROM stage_rank WHERE stage = stage.id ORDER BY rank_time DESC LIMIT 1) AS host_c
, (SELECT index_pa FROM stage_rank WHERE stage = stage.id ORDER BY rank_time DESC LIMIT 1) AS index_pa
, (SELECT links_pa FROM stage_rank WHERE stage = stage.id ORDER BY rank_time DESC LIMIT 1) AS links_pa
, (SELECT index_pb FROM stage_rank WHERE stage = stage.id ORDER BY rank_time DESC LIMIT 1) AS index_pb
, (SELECT links_pb FROM stage_rank WHERE stage = stage.id ORDER BY rank_time DESC LIMIT 1) AS links_pb
FROM stage
ORDER BY name;
我认为这主要是因为从stage_rank
重复选择,是否可以将此选择完成一次,并获得单击中的所有字段?
此外,任何postgresql特定的特性都可能对此有所帮助吗?
答案 0 :(得分:9)
在PostgreSQL
中,您可以选择整个记录作为字段并稍后展开:
SELECT id, name, (sr).*
FROM (
SELECT id, name,
(
SELECT stage_rank
FROM stage_rank
WHERE stage = stage.id
ORDER BY
rank_time DESC
LIMIT 1
) sr
FROM stage
) q
ORDER BY
name
或重写查询:
SELECT DISTINCT ON (s.name, s.id, sr.rank_time, sr.id)
s.id, s.name, sr.*
FROM stage s
JOIN stage_rank sr
ON sr.stage = s.id
ORDER BY
s.name, s.id, sr.rank_time DESC, sr.id DESC
或以其他方式重写:
SELECT id, name, (sr).*
FROM (
SELECT s.id, s.name, sr, ROW_NUMBER() OVER (PARTITION BY s.id ORDER BY sr.rank_time DESC, sr.id DESC) rn
FROM stage
JOIN stage_rank sr
ON sr.stage = s.id
) q
WHERE rn = 1
ORDER BY
name