我在jsonb类型的列中存储了以下JSON。我想查询外部数组的第二个元素,并将“cid”列中具有值的所有行过滤为“CID1”。
{"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 :(得分: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';