我有张桌子上有电子邮件:
email
- id : numeric, primary key
- id_in_target : text, the ID as stored in Google/MS, indexed
- in_reply_to : nullable, text, references id_in_target in case of a reply, indexed
- ts : timestamp, email's timestamp
... some other columns给定一个电子邮件ID列表,我试图获取受电子邮件ID列表影响的所有回复或源电子邮件。因此,电子邮件表是与自己连接的。查询有以下形式:
select reply.id, extract(epoch from (source.ts - reply.ts))
from email source
join email reply on source.id_in_target = reply.in_reply_to
where source.id in (ids) or reply.id in (ids)问题在于主键上的OR条件。如果我只选择源或回复,优化器将使用主键。但是,在OR条件下,计划者选择扫描整个表。我知道我可以用union“复制”查询,但我只是不明白为什么它会选择次优方案,而这显然是一个主要的关键条件。
发布于 2022-08-30 16:53:42
这是因为OR。PostgreSQL不能自动将查询重写为两个查询的UNION,因为它不能证明结果是相同的:带有OR的查询可以返回两个相同的结果行,而UNION查询不能。
https://dba.stackexchange.com/questions/316225
复制相似问题