PostgreSQL wildcard LIKE for any of a list of words

前端 未结 5 1079
醉酒成梦
醉酒成梦 2020-11-29 15:47

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

相关标签:
5条回答
  • 2020-11-29 16:29

    You can use Postgres' SIMILAR TO operator which supports alternations, i.e.

    select * from table where lower(value) similar to '%(foo|bar|baz)%';
    
    0 讨论(0)
  • 2020-11-29 16:32

    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.

    0 讨论(0)
  • 2020-11-29 16:37

    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

    0 讨论(0)
  • 2020-11-29 16:47

    PostgreSQL also supports full POSIX regular expressions:

    select * from table where value ~* 'foo|bar|baz';
    

    The ~* is for a case insensitive match, ~ is case sensitive.

    Another option is to use ANY:

    select * from table where value  like any (array['%foo%', '%bar%', '%baz%']);
    select * from table where value ilike any (array['%foo%', '%bar%', '%baz%']);
    

    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.

    0 讨论(0)
  • 2020-11-29 16:47

    Actually there is an operator for that in PostgreSQL:

    SELECT *
    FROM table
    WHERE lower(value) ~~ ANY('{%foo%,%bar%,%baz%}');
    
    0 讨论(0)
提交回复
热议问题