簡體   English   中英

檢查數組元素是否以特定字符postgres開頭

[英]Check if any of array elements starts with specific characters postgres

我正在嘗試檢查數組是否具有以指定的字符串開頭或結尾的任何元素。

對於比較字符串,我們可以執行以下操作,

select * from table where 'gggggg' ilike '%g';

有人可以幫忙找出數組是否包含值(例如模式)。
例如數組:['str1','str2','str3']

我也想找到是否任何元素以1結尾或以'str'開頭。

現在,您唯一可以做的就是取消嵌套數組並測試每個元素:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM