postgresql - postgres _ 中的特殊字符

标签 postgresql

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

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。

最佳答案

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

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

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

关于postgresql - postgres _ 中的特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14341438/

相关文章:

database - 在 Heroku 上运行应用程序,但在别处运行数据库

json - 按 JSON 数据类型排序 postgres

django - ValueError : Cannot add *: instance is on database "default", 值在数据库 "None"上

postgresql - 查找具有重叠范围的行

javascript - Servoy - 从数据库表中获取所有数据以显示为列表

sql - 用于填充记录集和返回 ID 的 Postgres 函数

sql - 如何通过 with 语句连接 postgresql 中的 3 个表

如果列被切换,SQL 添加行的值

案例中的 SQL 顺序、DESC 和 ASC 奇怪行为

sql - 在 postgresql 中使用 nanosec 存储时间戳最优雅的方法是什么?