假设我们有一个 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!
是的,这可以通过 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;
请注意,使用标准化数据设计会更容易、更快。