PostgreSQL 反向 LIKE

PostgreSQL Reverse LIKE

我需要测试列值的任何部分是否在给定字符串中,而不是字符串是否是列值的一部分。 例如:

这样,我可以找到 table 中的任何行是否包含 column 中的字符串 'bricks':

SELECT column FROM table
WHERE column ILIKE '%bricks%';

但我要查找的是找出句子“The ships hanged in the sky in much the same way that bricks don't " 在任何行中。 类似于:

SELECT column FROM table
WHERE 'The ships hung in the sky in much the same way that bricks don’t' ILIKE '%' || column || '%';

因此,第一个示例中列包含 'bricks' 的行将显示为结果。

我查看了这里和其他一些论坛的一些建议,但 none 行得通。

这个查询:

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

给出以下结果:

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

现在只需对该查询的结果进行半连接以获得所需的结果

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 || '%'
)  

您的简单案例可以通过使用 ANY 构造和 ~*:

的简单查询来解决
SELECT *
FROM   tbl
WHERE  col ~* ANY (string_to_array('The ships hung in the sky ... bricks don’t', ' '));

~* 是不区分大小写的正则表达式匹配运算符。我使用它而不是 ILIKE,这样我们就可以在您的字符串中使用原始单词,而无需为 ILIKE 填充 %。结果是相同的 - 除了包含特殊字符的单词:%_\ 表示 ILIKE!$()*+.:<=>?[\]^{|}- 表示正则表达式模式。您可能需要以任何一种方式转义特殊字符以避免意外。这是正则表达式的函数:

  • Escape function for regular expression or LIKE patterns

但我一直怀疑这将是您所需要的全部。看我的评论。我怀疑您需要使用自然语言匹配词典的全文搜索来提供有用的词干提取...

相关: