gpt4 book ai didi

sql - 使用 A Union B 与 Where A OR B 的 Postgres 性能

转载 作者:行者123 更新时间:2023-11-29 14:31:01 25 4
gpt4 key购买 nike

我想知道联合是否会以与 where 子句相同的速度运行。

注意:我确实在任何相关列上放置了索引

例如

-- Using where or condition
select group, name from jobs where group = 'a' or group = 'b'

-- Using union's to achieve the same result
select group, name from jobs where group = 'a'
union
select group, name from jobs where group = 'a'

在上面的示例中,一种技术会更快吗?或者它们会以相同的速度执行

我问的原因是我需要使用 similarity, trigrams 或 ts_vectors 进行模糊匹配,其中需要返回实际匹配的过滤条件,以便我知道如何找到特定行.

例如

-- Using where or condition
select description from jobs where
description = to_tsvector('english', description) @@ to_tsquery('english', 'ability <-> to <-> motivate <-> others')
or
description = to_tsvector('english', description) @@ to_tsquery('english', 'excellent <-> organisational <-> skills')

-- NOTE: When using (where OR) I have no way of telling which condition actually matched

-- Using union's to achieve the same result
select 'ability to motivate others' as search_term, description
from jobs
where description = to_tsvector('english', description) @@ to_tsquery('english', 'ability <-> to <-> motivate <-> others')
union
or
select 'excellent organisational skills' as search_term, description
from jobs
where description = to_tsvector('english', description) @@ to_tsquery('english', 'excellent <-> organisational <-> skills')

最佳答案

union 以与where相同的速度运行条款。 union会产生删除重复项的开销,这通常意味着对数据进行排序。这就是为什么 union all首选,如果可以达到相同的结果集。

也就是说,有时子查询与 union 一起使用/union all可以比使用 or 的相同查询更好地优化在whereon条款。

所以,不可能说union在这种情况下总是不好的。一个合理的观点是 union会产生额外的开销。如果可以优化子查询,这种开销可能并不重要,但通常情况下,union会影响性能。

关于sql - 使用 A Union B 与 Where A OR B 的 Postgres 性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51868008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com