1

我有一个这样的查询,它在 call_id 上使用索引,而如果我在值中添加 _,那么它会从索引搜索变为 seq 搜索。

explain analyze 
DELETE 
FROM completedcalls 
WHERE call_id like '560738a563616c6c004c7621@198.148.114.67-b2b1';


                                                           QUERY PLAN                                                           
--------------------------------------------------------------------------------------------------------------------------------
 Delete on completedcalls  (cost=0.00..8.67 rows=1 width=6) (actual time=0.036..0.036 rows=0 loops=1)
   ->  Index Scan using i_call_id on completedcalls  (cost=0.00..8.67 rows=1 width=6) (actual time=0.034..0.034 rows=0 loops=1)
         Index Cond: ((call_id)::text = '560738a563616c6c004c7621@198.148.114.67-b2b1'::text)
         Filter: ((call_id)::text ~~ '560738a563616c6c004c7621@198.148.114.67-b2b1'::text)
 Total runtime: 0.069 ms
(5 rows)

这个说法:

explain analyze 
DELETE 
FROM completedcalls 
WHERE call_id like '560738a563616c6c004c7621@198.148.114.67-b2b_1';

返回此执行计划:

QUERY PLAN                                                       
-----------------------------------------------------------------------------------------------------------------------
 Delete on completedcalls  (cost=0.00..39548.64 rows=84 width=6) (actual time=194.313..194.313 rows=0 loops=1)
   ->  Seq Scan on completedcalls  (cost=0.00..39548.64 rows=84 width=6) (actual time=194.310..194.310 rows=0 loops=1)
         Filter: ((call_id)::text ~~ '560738a563616c6c004c7621@198.148.114.67-b2b_1'::text)
 Total runtime: 194.349 ms
(4 rows)

我的问题是如何在查询中转义这些字符。在 python 中使用 psycopg2。

4

1 回答 1

4

您需要_使用反斜杠转义,如下所示:

DELETE FROM completedcalls 
WHERE call_id like '560738a563616c6c004c7621@198.148.114.67-b2b\_1';

此外,如果您不想要模式匹配,使用=而不是LIKE.

于 2013-01-15T15:54:01.687 回答