【发布时间】:2015-12-24 22:27:03
【问题描述】:
运行以下查询时,有时需要 15 秒,有时需要 90 分钟。是什么导致了如此大的差异?
INSERT INTO missing_products
SELECT table_name,
product_id
FROM products
WHERE table_name = 'xxxxxxxxx'
AND product_id NOT IN (SELECT id
FROM new_products);
我已尝试对此进行解释,但我唯一能看到的是关于新产品的index only scan。我也重写了这个查询,改为使用左连接并插入右侧为 NULL 的行,但这会导致同样的时间问题。
我有以下表格,其结构类似于以下内容。
产品
id bigint not null,
product_id text not null,
table_name text not null,
primary key (id),
unique index (product_id)
新产品
id text not null,
title text not null,
primary key, btree (id)
缺少的产品
table_name text not null,
product_id text not null,
primary key (table_name, product_id)
解释 - 这在 where 子句中有一个额外的字段,但应该提供一个好主意。耗时 22 秒。
Insert on missing_products (cost=5184.80..82764.35 rows=207206 width=38) (actual time=22466.525..22466.525 rows=0 loops=1)
-> Seq Scan on products (cost=5184.80..82764.35 rows=207206 width=38) (actual time=0.055..836.217 rows=411150 loops=1)
Filter: ((active > (-30)) AND (NOT (hashed SubPlan 1)) AND (feed = 'xxxxxxxx'::text))
Rows Removed by Filter: 77436
SubPlan 1
-> Index Only Scan using new_products_pkey on new_products (cost=0.39..5184.74 rows=23 width=10) (actual time=0.027..0.027 rows=0 loops=1)
Heap Fetches: 0
Planning time: 0.220 ms
Execution time: 22466.596 ms
【问题讨论】:
-
请提供
EXPLAIN ANALYZE输出,这将帮助我们了解是否有任何触发器可能导致缓慢
标签: sql postgresql