我的查询速度很慢(> 1s)。以下是该查询的explain analyze
结果:
Nested Loop Left Join (cost=0.42..32275.13 rows=36 width=257) (actual time=549.409..1106.044 rows=2 loops=1)
Join Filter: (answer.lt_surveyee_survey_id = lt_surveyee_survey.id)
-> Index Scan using lt_surveyee_survey_id_key on lt_surveyee_survey (cost=0.42..8.44 rows=1 width=64) (actual time=0.108..0.111 rows=1 loops=1)
Index Cond: (id = 'xxxxx'::citext)
-> Seq Scan on answer (cost=0.00..32266.24 rows=36 width=230) (actual time=549.285..1105.910 rows=2 loops=1)
Filter: (lt_surveyee_survey_id = 'xxxxx'::citext)
Rows Removed by Filter: 825315
Planning time: 0.592 ms
Execution time: 1106.124 ms
结果的xxxxx
部分类似于uuid。我没有建立那个数据库,所以我现在没有任何线索。这是查询:
EXPLAIN ANALYZE SELECT
lt_surveyee_survey.id
-- +Some other fields
FROM lt_surveyee_survey
LEFT JOIN answer ON answer.lt_surveyee_survey_id = lt_surveyee_survey.id
WHERE lt_surveyee_survey.id = 'xxxxx';
答案 0 :(得分:0)
JOIN
根据EXPLAIN ANALYZE
输出导致性能下降。您可以看到有2个不同的查找,一个花了几毫秒,另一个花了半秒钟。
差异由行的开头表示:Index Scan
和Seq Scan
,其中Seq
是顺序的缩写,这意味着所有行都必须由DBMS检查处理JOIN
。顺序扫描的原因是要检查的列上的缺少索引(在您的情况下为answer.lt_surveyee_survey_id
)。
添加索引应解决性能问题。