Postgresql json在9.3中查询嵌套的有效载荷
发布时间:2020-12-13 16:30:53 所属栏目:百科 来源:网络整理
导读:如果我有一个名为“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 },
如果我有一个名为“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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- c# – 为什么将委托声明为静态会导致编译器错误“修饰符’s
- Flex中QueryTask,FindTask,Indent…
- [Swift]:快速学习笔记5 扩展和泛型
- c# – 与对象包装类一起使用时的灵活性
- ruby-on-rails – 有没有选择生成脚手架而不产生迁移?
- [Swift]LeetCode211. 添加与搜索单词 - 数据结构设计 | Add
- swift – 在Xcode 7中构建Parse时的链接错误
- ios – 在Xcode中,图像大小应该是@ 1x,@ 2x和@ 3x?
- c# – DbSet.Add&DbSet.Remove使用EntityState.Added和
- XML Schema文档