【问题标题】:select from string from outcome of json file in postgresql从 postgresql 中 json 文件的结果中选择字符串
【发布时间】:2019-10-16 02:15:26
【问题描述】:

在 postgre sql 中,我的表有下面的 json 格式的属性列

{"color": true,"view": [184],"school": 
[805,812,855,856,857]} 

我想写一个专栏,如果学校包含805,812,855,则为1,否则为0。下面我尝试了,但它不起作用。

 case when  json_extract_path_text(attributes, 'school') in 
 [805,812,855] then 1 else 0 end as school

我该如何解决这个问题? 谢谢。

【问题讨论】:

    标签: json postgresql select contains


    【解决方案1】:

    您可以使用横向交叉连接为每一行创建一个数组,并查看它是否包含 [805,812,855] 中的值。在这里,我假设您要确保它包含所有值,而不是任何值。

    with data as (select * from (values
      ('{"color": true,"view": [184],"school":[805,812,855,856,857]}'::jsonb),
      ('{"color": true,"view": [184],"school":[805,812]}'::jsonb)
    ) as v(data))
    SELECT school_arr @> '{805,812,855}'
    FROM data
    CROSS JOIN LATERAL (SELECT ARRAY(SELECT jsonb_array_elements_text(data -> 'school'))) d(school_arr)
    ;
     ?column?
    ----------
     t
     f
    (2 rows)
    

    【讨论】:

      【解决方案2】:

      其实我得到了答案

      case when json_extract_path_text(attributes, 'school')::jsonb@>'805' then 1 
           when json_extract_path_text(attributes, 'school')::jsonb@>'812' then 1
           when json_extract_path_text(attributes, 'school')::jsonb@>'855' then 1
      else 
      0 end as school
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-30
        • 2018-10-10
        • 2021-12-11
        • 2017-08-17
        • 2015-03-31
        • 1970-01-01
        相关资源
        最近更新 更多