检查数组中的子字符串是否出现在字符串中?

时间:2017-04-03 12:53:28

标签: sql postgresql

我有以下查询:

select case when count(*)>0 then true else false end
from tab
where param in ('a','b') and position('T' in listofitem)>0

这会检查列'T'中是否存在listofitem,如果确实,则计数是>基本上它是搜索子字符串。

这在私人案件中效果很好。不过我的真实情况是text[]调用了sub_array,意味着要检查多个值。如何修改查询以处理sub_array类型?我更喜欢将它放在查询中而不是带有LOOP的函数中。

我真正需要的是:

select case when count(*)>0 then true else false end
from tab
where param in ('a','b') and position(sub_array in listofitem)>0

由于sub_array的类型为Text[]

,因此无效

2 个答案:

答案 0 :(得分:5)

使用unnest() function展开您的阵列& bool_and()(或bool_or() - 这取决于您想要匹配的内容:所有数组元素,或至少一个)到{{3} }:

select count(*) > 0
from   tab
where  param in ('a','b')
and    (select bool_and(position(u in listofitem) > 0)
        from   unnest(sub_array) u)

答案 1 :(得分:0)

强力方法是将数组转换为字符串:

select (count(*) > 0) as flag
from tab
where param in ('a','b') and
      array_to_string(listofitem, '') like '%T%';

我应该注意,比较count(*)并不是最有效的方法。我建议改为:

select exists (select 1
               from tab
               where param in ('a','b') and
                     array_to_string(listofitem, '') like '%T%'
              ) as flag;

这会在第一次匹配时停止逻辑,而不是计算所有匹配的行。

相关问题