在PostgreSQL数组中使用LIKE进行搜索

时间:2016-11-01 15:50:21

标签: arrays postgresql comparison-operators

我有这张桌子:

 id |   name   |          tags           
----+----------+-------------------------
  1 | test.jpg | {sometags,other_things}

我需要通过使用正则表达式或LIKE在数组中搜索来获取包含特定标记的行,如下所示:

SELECT * FROM images WHERE 'some%' LIKE any(tags);

但是这个查询什么都不返回。

1 个答案:

答案 0 :(得分:4)

with images (id, name, tags) as (values
    (1, 'test.jpg', '{sometags, other_things}'::text[]),
    (2, 'test2.jpg', '{othertags, other_things}'::text[])
)
select *
from images
where (
    select bool_or(tag like 'some%')
    from unnest(tags) t (tag)
);
 id |   name   |          tags           
----+----------+-------------------------
  1 | test.jpg | {sometags,other_things}

unnest会返回一个您使用方便的bool_or函数

进行汇总的集合