postgres中的特殊字符_

时间:2013-01-15 15:48:55

标签: postgresql

我有一个这样的查询,它在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。

1 个答案:

答案 0 :(得分:3)

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

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

此外,如果您不想进行模式匹配,使用=代替LIKE可能会更有意义。