PostgreSQL 通配符 LIKE 用于任何单词列表
我有一个大约 25 个单词的简单列表。我在 PostgreSQL 中有一个 varchar 字段,假设该列表是 ['foo', 'bar', 'baz']
。我想在表中找到包含这些单词的任何行。这会起作用,但我想要更优雅的东西。
select *
from table
where (lower(value) like '%foo%' or lower(value) like '%bar%' or lower(value) like '%baz%')
I have a simple list of ~25 words. I have a varchar field in PostgreSQL, let's say that list is ['foo', 'bar', 'baz']
. I want to find any row in my table that has any of those words. This will work, but I'd like something more elegant.
select *
from table
where (lower(value) like '%foo%' or lower(value) like '%bar%' or lower(value) like '%baz%')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
PostgreSQL 还支持完整的 POSIX 正则表达式 :
~*
不区分大小写,~
区分大小写。另一种选择是使用 ANY:
您可以将 ANY 与任何产生布尔值的运算符一起使用。我怀疑正则表达式选项会更快,但 ANY 是您工具箱中的一个有用工具。
PostgreSQL also supports full POSIX regular expressions:
The
~*
is for a case insensitive match,~
is case sensitive.Another option is to use ANY:
You can use ANY with any operator that yields a boolean. I suspect that the regex options would be quicker but ANY is a useful tool to have in your toolbox.
您可以使用 Postgres 的
类似于< /code>
支持交替的运算符,即
You can use Postgres'
SIMILAR TO
operator which supports alternations, i.e.实际上 PostgreSQL 中有一个运算符:
Actually there is an operator for that in PostgreSQL:
一种“优雅”的解决方案是使用全文搜索:http://www.postgresql.org/docs/9.0/interactive/textsearch.html" postgresql.org/docs/9.0/interactive/textsearch.html。然后您将使用全文搜索查询。
One 'elegant' solution would be to use full text search: http://www.postgresql.org/docs/9.0/interactive/textsearch.html. Then you would use full text search queries.
当前支持的所有版本(9.5 及更高版本)除了
LIKE
之外还允许模式匹配。参考: https://www.postgresql.org/docs/current/functions-匹配.html
All currently supported versions (9.5 and up) allow pattern matching in addition to
LIKE
.Reference: https://www.postgresql.org/docs/current/functions-matching.html