【问题标题】:Find intersection with given list查找与给定列表的交集
【发布时间】:2021-08-06 06:56:50
【问题描述】:

我有一个文件路径表,其中包含其内容的哈希值,可能有多个文件具有相同的哈希值。

create table files(
  path varchar(256) not null,
  hash varchar(100) not null
);

create index files_hash on files (hash);

鉴于我有 3 个哈希数组 'a', 'b', 'c',我如何有效地找到 files 表包含哪些哈希?

我可以使用select distinct hash 来获取files 中存在的哈希:

select distinct hash
from   files
where  hash in ('a', 'b', 'c')

但它会有效吗?就像说有数十万个带有哈希 'a' 的文件,PostgreSQL 会遍历所有这些记录吗?有没有办法告诉它一找到第一个就立即停止?

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    这应该尽可能快:

    SELECT * 
    FROM   unnest('{a,b,c}'::varchar[]) AS arr(hash)
    WHERE  EXISTS (SELECT FROM files f WHERE f.hash = arr.hash);
    

    如果您的表足够 VACUUM'ed,那么无论有多少哈希匹配,您都可以在 files_hash 索引上进行仅索引扫描,并具有恒定(出色)的性能。见:

    【讨论】:

      【解决方案2】:

      如果你想要一个数组中的所有哈希值,我建议:

      select distinct hash
      from files
      where hash = any(array['a', 'b', 'c']);
      

      为了获得此查询的性能,您需要files(hash) 上的索引。

      如果您只希望返回一个,那么这应该更快:

      select hash
      from files
      where hash = any(array['a', 'b', 'c'])
      limit 1;
      

      【讨论】:

        猜你喜欢
        • 2019-02-14
        • 2015-03-06
        • 2013-03-28
        • 1970-01-01
        • 1970-01-01
        • 2010-10-13
        • 2013-10-12
        • 2021-03-18
        • 1970-01-01
        相关资源
        最近更新 更多