【发布时间】:2019-05-07 19:49:53
【问题描述】:
我的数据库的一列中有一个类似于此结构的 json 数组 -
{
"id": "123abc",
"Y/N": "Y",
"Color": "Purple",
"arr": [ {
"time": 1210.55
"person": "Sean"
"action": "yes" //The values for this field can only be 'yes', 'no, 'maybe'
},
{
"time": 1230.19
"person": "Linda"
"action": "no"
} ],
}
我需要根据“arr”数组中对象的 2 个条件提取所有相应的属性。我想根据“时间”(最大值)获取最新的“arr”对象,但仅在"action" 等于“否”或“是”时才拉出此索引,因此当"action" = "maybe" 时排除所有对象.
我尝试使用WHERE 语句设置“时间”范围并使用ORDER BY DESC 提取最新条目并返回整个“arr”。这只是返回“时间”的最大值,但在 "action" = "maybe" 时返回所有属性,但我想返回只有“是”或“否”的对象。
这是我当前的查询 -
SELECT jsonb_build_object('ID', t.col -> '_id',
'Yes or No', t.col -> 'Y/N',
'arr', x.elem)
FROM tbl t
CROSS JOIN LATERAL (
SELECT elem
FROM jsonb_array_elements(t.col -> 'arr') a(elem)
WHERE a.elem -> 'time' between '1110.23' and '1514.12'
AND t.col ->> 'Color' = 'Purple'
ORDER BY a.elem -> 'time' DESC NULLS LAST
LIMIT 1
) x;
查询返回数组中时间最长的最新对象,但同时返回 "action" = "maybe" 时的对象。我尝试在 WHERE 语句后添加 AND a.elem -> 'action' = 'yes',但收到错误消息,提示令牌“是”无效。
是否可以返回一个“时间”最大的对象,其“动作”属性仅等于“是”或“否”?
【问题讨论】:
标签: sql arrays json postgresql