为PostgreSQL调整以下SQL的最佳方法是什么,这似乎非常昂贵?创建临时表会产生最优成本吗?
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;
答案 0 :(得分:0)
如果您按照以下方式说出查询:
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)
等检查。