在 PostgreSQL 中查询 JSON 对象中数组的特定元素

问题描述 投票:0回答:1

假设我们有一个 PostgreSQL 数据库,其中有一个表,其中包含 json 行的汽车和事件

brand | events
---+-----------------
audi  | JSON Object
ford  | JSON Object
bmw   | JSON Object
...

JSON 具有以下结构:

{
    "type": "events",
    "data": [
        {
            "event": "foo",
            "timestamp": "2024-02-09T14:07:36"
        },
        {
            "event": "foo",
            "timestamp": "2024-02-10T14:07:36"
        },
        {
            "event": "bar",
            "timestamp": "2024-02-11T14:07:36"
        },
        {
            "event": "foo",
            "timestamp": "2024-02-12T14:07:36"
        },
        {
            "event": "bar",
            "timestamp": "2024-02-13T14:07:36"
        }
    ]
}

如何查询表中满足以下条件的行:

每辆车的事件应包含一个“bar”事件。

输出应如下所示:

brand | last_bar_timestamp
---+-----------------
audi  | Timestamp
ford  | Timestamp
bmw   | Timestamp
...

其中“last_bar_timestamp”是具有最新日期的特定汽车的“bar”事件。

使用 PostgreSQL 提供的 json 函数可以实现吗?

                          Thanks!                       
arrays json postgresql
1个回答
0
投票

是的,这可以通过 PostgreSQL 提供的 json 函数实现。使用横向子查询

jsonb_array_elements
。我假设您的
events
列类型是 JSONB 而不是 JSON。

with t as
(
 select brand, (j ->> 'timestamp')::timestamp last_bar_timestamp
 from the_table, lateral jsonb_array_elements(events -> 'data') j
 where j ->> 'event' = 'bar'
)
select distinct on (brand) *
from t
order by brand, last_bar_timestamp desc;

DB 填充

请注意,使用标准化数据设计会更容易、更快。

© www.soinside.com 2019 - 2024. All rights reserved.