如何在 Postgresql 中转义下划线
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38084864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to escape underscores in Postgresql
提问by Joe M
When searching for underscores in Postgresql, literal use of the character _
doesn't work. For example, if you wanted to search all your tables for any columns that ended in _by
, for something like change log or activity information, e.g. updated_by
, reviewed_by
, etc., the following query almost works:
在 Postgresql 中搜索下划线时,字符的字面使用_
不起作用。例如,如果你想搜索,在结束的列所有的表_by
,这样的事情更改日志或活动信息,例如updated_by
,reviewed_by
等等,下面的查询工作差不多:
SELECT table_name, column_name FROM information_schema.columns
WHERE column_name LIKE '%_by'
It basically ignores the underscore completely and returns as if you'd searched for LIKE '%by'
. This may not be a problem in all cases, but it has the potential to be one. How to search for underscores?
它基本上完全忽略下划线并返回,就像您搜索LIKE '%by'
. 这可能不是所有情况下的问题,但它有可能成为一个问题。如何搜索下划线?
回答by Joe M
You need to use a backslash to escape the underscore. Change the example query to the following:
您需要使用反斜杠来转义下划线。将示例查询更改为以下内容:
SELECT table_name, column_name FROM information_schema.columns
WHERE column_name LIKE '%\_by'
回答by Taylor D
Just ran into the same issue and the single backslash wasn't working as well. I found this documentation on the PostgreSQL community and it worked:
刚遇到同样的问题,单个反斜杠也不起作用。我在 PostgreSQL 社区上找到了这个文档并且它有效:
The correct way is to escape the underscore with a backslash. You actually have to write two backslashes in your query:
select * from foo where bar like '%\\_baz'
The first backslash quotes the second one for the query parser, so that what ends up inside the system is %\_baz, and then the LIKE function knows what to do with that.
正确的方法是用反斜杠转义下划线。您实际上必须在查询中写入两个反斜杠:
select * from foo where bar like '%\\_baz'
第一个反斜杠引用查询解析器的第二个反斜杠,因此系统内部最终是 %\_baz,然后 LIKE 函数知道如何处理它。
Therefore use something like this:
因此使用这样的东西:
SELECT table_name, column_name FROM information_schema.columns
WHERE column_name LIKE '%\_by'
Source Documentation: https://www.postgresql.org/message-id/10965.962991238%40sss.pgh.pa.us
源文档:https: //www.postgresql.org/message-id/10965.962991238%40sss.pgh.pa.us