我有一个列open_houses
,它是JSON数据类型,它看起来像这样:
open_houses
[{"Date": "2017-08-13", "ToTime": "4:00PM", "FromTime": "2:00PM"}]
[{"Date": "2017-08-12", "ToTime": "3:00PM", "FromTime": "1:00PM"}]
[{"Date": "2017-08-12", "ToTime": "4:00PM", "FromTime": "2:00PM"}]
[{"Date": "2017-08-13", "ToTime": "3:00PM", "FromTime": "1:00PM"}]
当我尝试从此列中提取“日期”时,我收到错误 -
SELECT ...
FROM prod.vw_listing
WHERE ...
...
AND open_houses[1] -> 'Date'::DATE >= current_date;
错误:
cannot subscript type jsonb because it is not an array
答案 0 :(得分:2)
使用->
操作数获取json数组元素:
with vw_listing (open_houses) as ( values
('[{"Date": "2017-08-13", "ToTime": "4:00PM", "FromTime": "2:00PM"}]'::jsonb),
('[{"Date": "2017-08-12", "ToTime": "3:00PM", "FromTime": "1:00PM"}]'),
('[{"Date": "2017-08-12", "ToTime": "4:00PM", "FromTime": "2:00PM"}]'),
('[{"Date": "2017-08-13", "ToTime": "3:00PM", "FromTime": "1:00PM"}]')
)
select (open_houses -> 0 ->> 'Date')::date
from vw_listing
;
date
------------
2017-08-13
2017-08-12
2017-08-12
2017-08-13
答案 1 :(得分:1)
我能够通过这样做来解决这个问题:
SELECT ...
FROM prod.vw_listing
WHERE ...
AND (open_houses -> 0 ->> 'Date')::date>= current_date;
答案 2 :(得分:0)
您还可以使用以下选择:
select (open_houses#>> '{0, Date}')::date
等同于选择open_houses[0]['Date']
之类的元素