我正在尝试检查数组是否具有以指定字符串开头或结尾的任何元素。
对于比较字符串,我们可以执行以下操作,
select * from table where 'gggggg' ilike '%g';
有人可以帮助您确定数组是否包含类似于模式的值。
例如:['str1','str2','str3']
我还要查找元素是否以1结尾或以'str'开头。
答案 0 :(得分:1)
目前,您唯一可以做的就是取消嵌套数组并测试每个元素:
create table test (a text[]);
insert into test values (array['abc', 'def', 'ghi']);
select distinct a from test
JOIN lateral (select * from unnest(a) as u) as sub on TRUE
WHERE u like '%g';
a
---
(0 rows)
select distinct a from test
JOIN lateral (select * from unnest(a) as u) as sub on TRUE
WHERE u like 'g%';
a
---------------
{abc,def,ghi}
(1 row)
在postgres 12中,您将可以使用jsonb_path_exists。当然,如果将数据存储在jsonb中,这样做会更好,但是仍然可以,只是效率不高:
-- Starts with g
select a from test
where jsonb_path_exists(to_jsonb(a), '$[*] ? (@ like_regex "^g")');
a
---------------
{abc,def,ghi}
(1 row)
-- Ends with g
select a from test
where jsonb_path_exists(to_jsonb(a), '$[*] ? (@ like_regex "g$")');
a
---
(0 rows)