Postgresql 加快查询速度,其中我对唯一键和另一个键进行排序
作为查询的一部分(实际上连接的一侧) 在shop_id和id上有btree索引,但由于某些原因,没有使用它们。Postgresql 加快查询速度,其中我对唯一键和另一个键进行排序,postgresql,Postgresql,作为查询的一部分(实际上连接的一侧) 在shop_id和id上有btree索引,但由于某些原因,没有使用它们。 解释分析说: -> Unique (cost=724198.71..742348.37 rows=360949 width=71) (actual time=179157.101..195998.646 rows=1673170 loops=1) -> Sort (cost=724198.71..733273.54 rows=3629931 wi
解释分析
说:
-> Unique (cost=724198.71..742348.37 rows=360949 width=71) (actual time=179157.101..195998.646 rows=1673170 loops=1)
-> Sort (cost=724198.71..733273.54 rows=3629931 width=71) (actual time=179157.095..191853.377 rows=3599644 loops=1)
Sort Key: products.shop_id, products.id
Sort Method: external merge Disk: 285064kB
-> Seq Scan on products (cost=0.00..328690.31 rows=3629931 width=71) (actual time=0.025..7575.905 rows=3629713 loops=1)
我还尝试在shop_id和id上创建一个多色btree索引,但没有使用。。(也许我做错了,不得不重新启动postgresql和所有东西?)
如何加速此查询(使用索引或其他什么?)
在所有三个上添加多列索引(“使用btree(shop_id,id,color)在产品上创建索引产品_idx”)不会被使用。
我进行了实验,如果我将上限设置为10000,则将使用:
Limit (cost=0.00..161337.91 rows=10000 width=14) (actual time=0.043..15.973 rows=10000 loops=1)
-> Unique (cost=0.00..2925620.98 rows=181335 width=14) (actual time=0.042..15.249 rows=10000 loops=1)
-> Index Scan using products_idx on products (cost=0.00..2922753.69 rows=1146917 width=14) (actual time=0.041..12.927 rows=14004 loops=1)
Total runtime: 16.293 ms
大约有3*10^6个条目(300万)
对于更大的限制,它再次使用顺序扫描:(
(我还必须将这里的work\u mem提高到128MB,否则会有一个需要更长时间的外部合并)您是否尝试了
上的索引(shop\u id,id,color)
那么Postgres可能只进行索引扫描。另外,你的排序是在磁盘上完成的,如果你增加这个查询的work\u mem
,这样它就会在内存中发生,这也会加快速度。好主意,我会试试:)@a\u horse\u没有名字我试过,但出于某种原因它仍然没有使用索引
Limit (cost=0.00..161337.91 rows=10000 width=14) (actual time=0.043..15.973 rows=10000 loops=1)
-> Unique (cost=0.00..2925620.98 rows=181335 width=14) (actual time=0.042..15.249 rows=10000 loops=1)
-> Index Scan using products_idx on products (cost=0.00..2922753.69 rows=1146917 width=14) (actual time=0.041..12.927 rows=14004 loops=1)
Total runtime: 16.293 ms
Limit (cost=213533.52..215114.73 rows=50000 width=14) (actual time=816.580..835.075 rows=50000 loops=1)
-> Unique (cost=213533.52..219268.11 rows=181335 width=14) (actual time=816.578..831.963 rows=50000 loops=1)
-> Sort (cost=213533.52..216400.81 rows=1146917 width=14) (actual time=816.576..823.034 rows=80830 loops=1)
Sort Key: shop_id, id
Sort Method: quicksort Memory: 107455kB
-> Seq Scan on products (cost=0.00..98100.17 rows=1146917 width=14) (actual time=0.019..296.867 rows=1146917 loops=1)
Total runtime: 840.788 ms