代码之家  ›  专栏  ›  技术社区  ›  Phillip Stack

从表中选择列值与数组中的任何项匹配的行

  •  0
  • Phillip Stack  · 技术社区  · 4 年前

    我想对列执行不区分大小写的匹配,查找给定字符串数组的任何匹配。

    例子:

    如果一行包含值

    id, comment
    1, 'This is my comment'
    

    我试图匹配数组中的任何一个词 ('statement','term','comment')

    我很想提出这样的问题

    SELECT * 
    FROM table_name 
    WHERE ( string_to_array(comment, ' ')  ANY ('{term}') );
    

    现在我明白了ANY函数旨在应用于数组列,但这实际上是我想要实现的。

    我试图避免的是必须迭代所有术语,并为每个术语执行单独的查询,然后必须删除重复项等。

    编辑:

    所以我能够找到一个似乎有效的解决方案。尽管我仍然希望得到更多的反馈,以确定这是否是一个合理的方法。

    SELECT * FROM table_name WHERE string_to_array(LOWER(column_name), ' ')::varchar[] && '{term1,term2,term3}'::varchar[];
    
    0 回复  |  直到 4 年前
        1
  •  0
  •   Sharif    4 年前

    以下是实现这一目标的两种方法:

    1. 使用任何&;条款安排
    SELECT * FROM
    (SELECT 1 id , 'This is my comment' comment1
    UNION
    SELECT 2, 'Another statement') data
    WHERE comment1 ~~ ANY(ARRAY['%comment%', '%statement%'])
    
    1. 类似
    SELECT * FROM
    (SELECT 1 id , 'This is my comment' comment1
    UNION
    SELECT 2, 'Another statement') data
    WHERE comment1 SIMILAR TO '%(comment|statement)%'