2017-01-29 35 views
0

我在jsonb類型的列中存儲了以下JSON。我想查詢外部數組的第二個元素,並過濾'cid'列中值爲'CID1'的所有行。在PostgreSQL上過濾JSONB列不起作用

{"root":[[ 
      {"cid":"CID1","Display":"User One","FName":"User","LName":"One"}, 
      {"cid":"CID1","Display":"User Two","FName":"User","LName":"Two"}, 
      {"cid":"CID1","Display":"User Three","FName":"User","LName":"Three"}, 
      {"cid":"CID2","Display":"User One","FName":"User","LName":"One"}, 
      {"cid":"CID2","Display":"User Two","FName":"User","LName":"Two"}, 
      {"cid":"CID2","Display":"User Three","FName":"User","LName":"Three"}  

      ], 
      [ 
      {"cid":"CID1","Display":"User One","FName":"Userfff","LName":"One"}, 
      {"cid":"CID1","Display":"User Two","FName":"User","LName":"Two"}, 
      {"cid":"CID1","Display":"User Three","FName":"User","LName":"Three"}, 
      {"cid":"CID2","Display":"User One","FName":"User","LName":"One"}, 
      {"cid":"CID2","Display":"User Two","FName":"User","LName":"Two"}, 
      {"cid":"CID2","Display":"User Three","FName":"User","LName":"Three"}  
      ]]} 

我寫了下面的查詢,併成功地但是從第二數組作爲JSON對象檢索所有的行,當我嘗試對其進行過濾,得到錯誤

42703:列「 filterin」不存在

select jsonb_array_elements((ARRAY(select jsonb_array_elements(msg->'root') ele))[2]::jsonb) filterin 
from js 
where filterin->>'cid'='CID1'; 

我應該糾正下面的查詢,使我能夠在列過濾器?

+0

完美工作,感謝@Sami – puneet

+0

@Sami,你認爲把一個GIN索引上jsonb列會更好? – puneet

回答

1

輸出別名不能在WHERE部分中使用。你有兩個選擇:子查詢或複製定義。

select jsonb_array_elements((ARRAY(select jsonb_array_elements(msg->'root') ele))[2]::jsonb) filterin 
from js 
where jsonb_array_elements((ARRAY(select jsonb_array_elements(msg->'root') ele))[2]::jsonb)->>'cid'='CID1'; 

SELECT filterin FROM 
(select jsonb_array_elements((ARRAY(select jsonb_array_elements(msg->'root') ele))[2]::jsonb) filterin 
from js) data 
WHERE filterin->>'cid'='CID1';