在 PostgreSQL 中调整查询

Tuning a query in PostgreSQL

为 PostgresSQL 调整以下 SQL 的最佳方法是什么,这似乎非常昂贵?创建一个临时 table 会提供最优成本吗?

UPDATE table1
SET    id = qry.crmId
FROM   (
    SELECT b.id AS crmId, a.row
    FROM   table1 AS a INNER JOIN table2 AS b ON lower(a.email) = lower(b.email) AND b.id = (
                SELECT MIN(id)
                FROM   table2
                WHERE  email = b.email AND email IS NOT NULL AND
                created = (
                            SELECT MIN(created)
                            FROM   table2
                            WHERE  email = b.email
                            )
                LIMIT 1
                )
    WHERE a.email IS NOT NULL AND b.id IS NOT NULL AND a.id IS NULL
    ) AS qry
WHERE  table1.row = qry.row;

如果您这样表述查询:

update table1 t11
    set id = (select id
              from table1 t12
              where t12.email = t11.email and
                    t12.id is not null
              order by t12.created
              limit 1
             )
    where id is null and email is not null;

然后它可以利用 table1(id)table1(email, created, id) 上的索引。

您可能想要添加一个支票,例如 and exists (select 1 from table1 t12 where t12.email = t11.email and t12.email is not null and t12.id is not null)