我有一个选择查询,如下所示:
select distinct
...some fields
from
table_a,
table_b,
table_c,
...more tables
where
table_a.id = table_b.id and
... (rest of the tables) and
some_field_that_i_care_about = 42
order by
my_field
如果我按原样运行该查询,大约需要半秒才能得到我期望的结果。
尽管如此,如果我将相同的查询转换为 View (不包括 some_field_that_i_care_about = 42
条件),然后运行:
select *
from the_view
where some_field_that_i_care_about = 42
查询大约需要 40 秒才能返回相同的数据。
为什么会发生这种情况?
最佳答案
View 只是子查询的语法糖。此类子查询通常不会导致性能损失,因为它们可能是 flattened ,即合并到外部查询中。
但是,在这种情况下,ORDER BY 会阻止展平。
只需从 View 中删除 ORDER BY 即可;子查询的顺序是ignored by the outer query反正。 (如果要对结果进行排序,则必须在最外层查询中使用ORDER BY。)
关于sqlite - sqlite View 的性能损失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47116994/