【问题标题】:Check if any of array elements starts with specific characters postgres检查是否有任何数组元素以特定字符 postgres 开头
【发布时间】:2019-07-05 19:28:04
【问题描述】:

我正在尝试检查一个数组是否有任何以指定字符串开头或结尾的元素。

对于比较字符串,我们可以执行如下操作,

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

有人可以帮助找出数组是否包含类似于模式的值。
例如数组:['str1', 'str2', 'str3']

我还想知道是否有任何元素以 1 结尾或以“str”开头。

【问题讨论】:

    标签: sql ruby-on-rails postgresql


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 2016-05-17
      • 1970-01-01
      • 2014-12-10
      • 2019-08-04
      • 2021-12-03
      • 2023-01-01
      • 2022-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多