2017-05-08 39 views
1

我在Postgres数据库运行一个相对简单的查询:简单查询到很长一段时间

INSERT INTO tt (pid, trip_pid) SELECT stop_time.pid, trip.pid         
FROM stop_time, trip                   
WHERE stop_time.trip_id = trip.trip_id AND 
17 = trip.gtfsfeed_id 
AND 17 = stop_time.gtfsfeed_id 

TT是一个临时表,stop_time的包含约200万行,行程只包含大约50,000。这个查询在我的aws rds实例上运行了一个多小时,我不知道为什么。这个查询有没有可悲的低效率?

编辑:这里是EXPLAIN(我创建了一个新的临时表相同的列运行解释)

        QUERY PLAN         
-------------------------------------------------------------------------------- 
Insert on ll (cost=2604.38..75394.65 rows=1649975 width=8) 
    -> Hash Join (cost=2604.38..75394.65 rows=1649975 width=8) 
     Hash Cond: ((stop_time.trip_id)::text = (trip.trip_id)::text) 
     -> Seq Scan on stop_time (cost=0.00..49406.68 rows=1835694 width=34) 
       Filter: (gtfsfeed_id = 17) 
     -> Hash (cost=2123.74..2123.74 rows=38451 width=34) 
       -> Seq Scan on trip (cost=0.00..2123.74 rows=38451 width=34) 
        Filter: (gtfsfeed_id = 17) 
+0

你能向我们展示查询的'EXPLAIN PLAN'吗? –

+0

我已经添加了它 – Derongan

+0

尝试使用forall语句批量插入。 – Avi

回答

1

您的tripstop_time表中的顺序扫描表明,它们未在trip_id字段中编入索引。将trip_id索引添加到两个表中将显着改善JOIN

此外,在两个表中添加索引gtfsfeed_id将使查询更快,因为您的查询将结果限制为这些字段的特定值。

提示:添加JOINWHERE语句中使用的字段索引通常很有用。

1

检查该查询,mayby会更快

INSERT INTO tt (pid, trip_pid) 
SELECT stop_time.pid, trip.pid         
FROM stop_time st 
join trip t on t.trip_id = st.trip_id 
where t.gtfsfeed_id = 17 
and st.gtfsfeed_id = 17; 

,你可以添加索引列gtfsfeed_id

1

请参阅表统计数据是准确的,并尝试索引stop_time(gtfsfeed_id)和/或trip(gtfsfeed_id)