需要Postgresql,jsonb查询帮助

时间:2017-03-31 08:06:36

标签: postgresql jsonb

我非常非常尴尬。但是我需要帮助我的查询,提前谢谢。

我的jsonb(jsonb数组)是

 [  

   {  
      "id_contact":2,
      "contact_data":{  
         "NM_EMAIL":[  
            "234rtrt@oao.com.ru"
         ],
         "NM_PHONE":[  
            "849533574",
            "849533d575"
         ]
      },
      "resp_ls_data":[  
         "14",
         "11"
      ],
       "pr_from_head":true
   },
   {  
      "id_contact":8,
      "contact_data":{  
         "NM_EMAIL":[  
            "somfdf11m@a.il"
         ],
         "NM_PHONE":[  
            "89234511"
         ]
      },
      "resp_ls_data":[  
         null
      ],
       "pr_from_head":false
   }

]

我把查询想象成

select case when pr_from_head then jsonb_build_object('id_head_cont',id_contact)::text
        when not pr_from_head then id_contact::text
        when id_contact is null then NULL end as est_contact_id,
   contact_data,
   nullif(resp_ls_data, '[null]') resp_ls_array
  from jsonb_to_recordset('
  [  

   {  
      "id_contact":2,
      "contact_data":{  
         "NM_EMAIL":[  
            "234rtrt@oao.com.ru"
         ],
         "NM_PHONE":[  
            "849533574",
            "849533d575"
         ]
      },
      "resp_ls_data":[  
         "14",
         "11"
      ],
       "pr_from_head":true
   },
   {  
      "id_contact":8,
      "contact_data":{  
         "NM_EMAIL":[  
            "somfdf11m@a.il"
         ],
         "NM_PHONE":[  
            "89234511"
         ]
      },
      "resp_ls_data":[  
         null
      ],
       "pr_from_head":false
   }

]
') as ls(id_contact integer, contact_data jsonb, resp_ls_data jsonb,pr_from_head boolean) 

得到的结果为:

"est_contact_id"       ||   "contact_data"    || resp_ls_array"
"{""id_head_cont"": 2}"||   "{""NM_EMAIL"":.. || "[""14"", ""11""]"
"8"                    ||   "{""NM_EMAIL"":.."|| NULL

但我想要的结果是:

 "est_contact_id"       ||  "contact_data"    || 'resp_ls_array"
  "{""id_head_cont"": 2}"|| "{""NM_EMAIL"":.. || "14"
  "{""id_head_cont"": 2}"|| "{""NM_EMAIL"":.. || "11"
  "8"                    || "{""NM_EMAIL"":.."|| NULL

如果resp_ls_array不为null,我想将部分分开。 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您可以使用jsonb_array_elements()转换结果,就像在此伪代码中一样:

select est_contact_id, contact_data, value as resp_ls
from (

    <your query here>

) s
left join jsonb_array_elements(resp_ls_array) on true;

Test it here.