PostgreSQL下加速IN查询的方法

Fra*_*eil 6 postgresql performance

我有以下形式的查询:

SELECT * FROM twitter_personas WHERE twitter_user_id IN ($1, $2, $3, ..., $25000)
Run Code Online (Sandbox Code Playgroud)

IN 查询有 10 到 25000 个值。查询一次运行几分钟。我有近 500,000 个这样的查询要运行。

twitter_user_id 列已编入索引。关于如何加快速度的任何想法?

# \d twitter_personas
                                    Table "public.twitter_personas"
      Column      |          Type          |                         Modifiers                          
------------------+------------------------+------------------------------------------------------------
 persona_id       | uuid                   | not null
 twitter_user_id  | bigint                 | 
 screen_name      | character varying(40)  | not null
 avatar_url       | text                   | 
 hashval          | integer                | not null default nextval('personas_hashval_seq'::regclass)
Indexes:
    "twitter_personas_pkey" PRIMARY KEY, btree (persona_id)
    "index_twitter_personas_on_screen_name" UNIQUE, btree (screen_name)
    "index_twitter_personas_on_screen_name_persona_id" btree (screen_name, persona_id)
    "index_twitter_personas_twitter_user_id" btree (twitter_user_id) WHERE twitter_user_id IS NOT NULL
Run Code Online (Sandbox Code Playgroud)

Fra*_*ens 7

IN() 使用许多参数将导致许多情况下进行顺序表扫描。这可能会很慢,具体取决于表的大小和系统的速度。

创建一个包含所有变量的临时表并加入该表:

CREATE TEMP TABLE t AS 
  SELECT * FROM (VALUES(1),(2),(3)) x(twitter_user_id);

SELECT 
  twitter_personas.* 
FROM twitter_personas 
  JOIN t USING(twitter_user_id);
Run Code Online (Sandbox Code Playgroud)

使用 EXPLAIN 查看查询计划之间的差异。

  • 具有相同 `VALUE` 行构造函数的 [CTE](http://www.postgresql.org/docs/current/interactive/queries-with.html) 也能正常工作。甚至更快 - 它基本上是一个临时表,只是开销更少。 (3认同)