Postgresql json在9.3中查询嵌套的有效载荷

前端之家收集整理的这篇文章主要介绍了Postgresql json在9.3中查询嵌套的有效载荷前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果我有一个名为“races”的简单表,使用 postgresql 9.3(和新的json awesomne​​ss),它有两列描述,如:
race-id integer,race-data json

而且,json是每个种族的有效载荷

{      "race-time": some-date,"runners": [ { "name": "fred","age": 30,"position": 1 },{ "name": "john","age": 29,"position": 3 },{ "name": "sam","age": 31,"position": 2 } ],"prize-money": 200    }

如何查询表格:

1)sam已经到来的比赛1

2)sam已经来到第1名,约翰已经来到第2名

3)年龄大于30岁的跑步者人数> 5和奖金> 5000

到目前为止,我的实验(特别是查询嵌套阵列有效载荷)导致进一步使数据正常化,即创建一个名为跑步者的表来进行这种查询.理想情况下,我想使用这个新的fangled json查询awesomeness,但我似乎无法做出头或尾部相应的3个简单的查询.

您可以将json放在一个记录中,然后根据需要进行查询(参见 json functions):
with cte as (
    select
       race_id,json_array_elements(r.race_data->'runners') as d,(r.race_data->>'prize-money')::int as price_money
    from races as r
),cte2 as (
    select
        race_id,price_money,max(case when (d->>'position')::int = 1 then d->>'name' end) as name1,max(case when (d->>'position')::int = 2 then d->>'name' end) as name2,max(case when (d->>'position')::int = 3 then d->>'name' end) as name3
    from cte
    group by race_id,price_money
)
select *
from cte2
where name1 = 'sam' and name2 = 'john'

sql fiddle demo

由于您的JSON结构,这有点复杂.我认为,如果你改变你的结构,你的查询可能会更简单:

{
  "race-time": some-date,"runners":
   {
      "1": {"name": "fred","age": 30},"2": {"name": "sam","age": 31},"3": {"name": "john","age": 29}
   },"prize-money": 200
}

您可以使用 – >>和 – >运算符或json_extract_path_text函数获取所需的数据,然后在where子句中使用它:

select *
from races as r
where
    r.race_data->'runners'->'1'->>'name' = 'sam';

select *
from races as r
where
    json_extract_path_text(r.race_data,'runners','1','name') = 'sam' and
    json_extract_path_text(r.race_data,'2','name') = 'john';

select *
from races as r
where
    (r.race_data->>'prize-money')::int > 100 and
    (
        select count(*)
        from json_each(r.race_data->'runners')
        where (value->>'age')::int >= 30
    ) >= 2

sql fiddle demo

原文链接:https://www.f2er.com/postgresql/191635.html

猜你在找的Postgre SQL相关文章