PostgreSQL Reverse LIKE

后端 未结 2 1475
梦毁少年i
梦毁少年i 2020-12-22 02:32

I need to test if any part of a column value is in a given string, instead of whether the string is part of a column value. For instance:

This way, I can find if any

相关标签:
2条回答
  • 2020-12-22 03:00

    This query:

    SELECT 
    regexp_split_to_table(
      'The ships hung in the sky in much the same way that bricks don’t', 
      '\s' );
    

    gives a following result:

    | regexp_split_to_table |
    |-----------------------|
    |                   The |
    |                 ships |
    |                  hung |
    |                    in |
    |                   the |
    |                   sky |
    |                    in |
    |                  much |
    |                   the |
    |                  same |
    |                   way |
    |                  that |
    |                bricks |
    |                 don’t |
    

    Now just do a semijoin against a result of this query to get desired results

    SELECT * FROM table t
    WHERE EXISTS (
       SELECT * FROM (
          SELECT 
        regexp_split_to_table(
          'The ships hung in the sky in much the same way that bricks don’t', 
          '\s' ) x
       ) x
       WHERE t.column LIKE '%'|| x.x || '%'
    )  
    
    0 讨论(0)
  • 2020-12-22 03:10

    Your simple case can be solved with a simple query using the ANY construct and ~*:

    SELECT *
    FROM   tbl
    WHERE  col ~* ANY (string_to_array('The ships hung in the sky ... bricks don’t', ' '));
    

    ~* is the case insensitive regular expression match operator. I use that instead of ILIKE so we can use original words in your string without the need to pad % for ILIKE. The result is the same - except for words containing special characters: %_\ for ILIKE and !$()*+.:<=>?[\]^{|}- for regular expression patterns. You may need to escape special characters either way to avoid surprises. Here is a function for regular expressions:

    • Escape function for regular expression or LIKE patterns

    But I have nagging doubts that will be all you need. See my comment. I suspect you need Full Text Search with a matching dictionary for your natural language to provide useful word stemming ...

    Related:

    • IN vs ANY operator in PostgreSQL
    • PostgreSQL LIKE query performance variations
    • Pattern matching with LIKE, SIMILAR TO or regular expressions in PostgreSQL
    0 讨论(0)
提交回复
热议问题