我想在Postgres中使用SQL来提取数据,但是想进入JSON结果并且只提取我需要的数据。
如果我写(在Valentina工作室):
Select "data" from "cars"
第一行看起来像:
[{"Model": "Golf", "Make": "VW", "Engine": "2.9"},
{"Model": "M3", "Make": "BMW", "Engine": "3.0"}]
我想要的只是:
Golf, M3
或"Golf", "M3"
然后我也可以对"Make"
或"Engine"
基本上我不希望我的结果是JSON。
答案 0 :(得分:2)
SELECT string_agg(x->>'Model', ',')
FROM cars
CROSS JOIN LATERAL
jsonb_array_elements(data) x
GROUP BY cars;
┌────────────┐
│ string_agg │
├────────────┤
│ Golf,M3 │
└────────────┘
(1 row)
答案 1 :(得分:1)
with cars(data) as (
values
('[
{"Model": "Golf", "Make": "VW", "Engine": "2.9"},
{"Model": "M3", "Make": "BMW", "Engine": "3.0"}
]'::json)
)
select
elem->>'Model' as model,
elem->>'Make' as make,
elem->>'Engine' as engine
from cars,
lateral json_array_elements(data) elem
model | make | engine
-------+------+--------
Golf | VW | 2.9
M3 | BMW | 3.0
(2 rows)
答案 2 :(得分:0)
我想我也得到了我想要的东西(并按照我计划的方式融化):
select obj->'Model' as model, obj->'Make' as make,
obj->'Engine' as engine from data n, jsonb_array_elements(n.DATA) as obj
从上面我也可以使用:
select
elem->>'Model' as model,
elem->>'Make' as make ,
elem->>'Engine' as engine
from cars,
lateral jsonb_array_elements(data) elem;
感谢您的帮助!