SQL喜欢相似替代

2024-05-20 15:01:46 发布

您现在位置:Python中文网/ 问答频道 /正文

是否有其他解决方案可供使用,而不是像匹配开始?你知道吗

下面是我要匹配的查询,从使用like开始。你知道吗

explain analyze select * from completedcalls where call_id like 'GWYA4NvSLzoIcvA7RAtmn_a9IelwOQeH@209.44.103.3%';
                                                    QUERY PLAN                                                    
------------------------------------------------------------------------------------------------------------------
 Seq Scan on completedcalls  (cost=0.00..52659.96 rows=112 width=228) (actual time=1.541..249.857 rows=2 loops=1)
   Filter: ((call_id)::text ~~ 'GWYA4NvSLzoIcvA7RAtmn_a9IelwOQeH@209.44.103.3%'::text)
 Total runtime: 249.893 ms
(3 rows)

这是非常广泛的,因为它做序列扫描而不是索引扫描。由于like的性质,它不能在提供的列上使用索引。列的索引简单如下:

"i_call_id" btree (call_id)

有没有什么特殊的索引类可以帮助like提高速度,或者有没有其他方法不用like就可以达到同样的效果?你知道吗

使用的表脚本是:

              Table "public.completedcalls"
    Column     |           Type           |  Modifiers   
---------------+--------------------------+--------------
 call_id       | character varying(128)   | 
 sip_code      | integer                  | 
 duration      | integer                  | 
 setup_time    | timestamp with time zone | not null
 authname      | character varying(30)    | 
 src_sig_ip    | character varying(20)    | 
 dst_sig_ip    | character varying(20)    | 
 cld           | character varying(22)    | 
 cli           | character varying(22)    | 
Indexes:
    "i_call_id" btree (call_id)
    "i_dst_sig_ip" btree (dst_sig_ip)

Tags: textipidtimecalllikerowsdst
3条回答

LIKE索引使用(或缺少索引)的情况在doc中描述:

简而言之,您应该创建索引

create index i_call_id on completedcalls(call_id varchar_pattern_ops);

但请阅读上面链接的页面,了解注意事项。你知道吗

LIKE能够在带有尾随%的条件上使用索引。你知道吗

优化器可能认为完全扫描比索引扫描更好,因为后者需要对其他列和记录可见性范围进行额外的表查找。你知道吗

^{} statements can still be used with b-tree indexes,假设没有前导通配符:

The optimizer can also use a B-tree index for queries involving the pattern matching operators LIKE and ~ if the pattern is a constant and is anchored to the beginning of the string — for example, col LIKE 'foo%' or col ~ '^foo', but not col LIKE '%bar'.

如果您的索引没有被使用,那么这是因为这里显示的LIKE用法之外的原因。。。你知道吗

相关问题 更多 >