[英]Select in nested jsonb - postgresql
I had a hard time finding the values on a basis, as all the examples cite the same way of finding information in simple jsons.我很难在基础上找到值,因为所有示例都引用了在简单 json 中查找信息的相同方式。
But a friend from work gave me a solution and I came to share.但是一个工作的朋友给了我一个解决方案,我来分享一下。
the initial question was: How to make a select in a nested json???最初的问题是:如何在嵌套的 json 中制作 select?
A json like this:像这样的 json:
{
"vehicle":[
{
"vehicle_type":"Truck",
"car_make":"Lotus",
"car_model":"Esprit",
"quantity":7,
"seats":7,
"price_hour":16,
"price_day":147,
"color":[
"Purple",
"Pink",
"Blue",
"White"
]
}
]
}
To view the structure, you can use the https://jsoneditoronline.org/要查看结构,可以使用https://jsoneditoronline.org/
The answer I bring uses select with regex:我带来的答案使用 select 和正则表达式:
select * from example
where example.jsonTest->>'vehicle' ~ 'color"\s*:\s*"?.*?Blue.*"?';
and和
select * from example
where example.jsonTest->>'vehicle' ~ 'vehicle_type"\s*:\s*"?.*?SUV.*"?';
To be clear I left a working example in https://rextester.com/BQZP48785为了清楚起见,我在https://rextester.com/BQZP48785中留下了一个工作示例
** sorry for my bad english ** 对不起,我的英语不好
In order to determine the vehicle with color blue , and vehicle type with SUV , jsonb_array_elements()
function might be used to unnest the main array, and then putting (j.elm->>'vehicle_type') = 'SUV'
into the WHERE
clause would be enough for the second, while (j.elm->>'color')::jsonb? 'Blue'
为了确定车辆颜色为 blue ,车辆类型为SUV ,可以使用jsonb_array_elements()
function 取消嵌套主数组,然后将(j.elm->>'vehicle_type') = 'SUV'
放入WHERE
第二个子句就足够了,而(j.elm->>'color')::jsonb? 'Blue'
(j.elm->>'color')::jsonb? 'Blue'
should be used containing jsonb conversion with ? (j.elm->>'color')::jsonb? 'Blue'
应该使用包含jsonb转换的? operator for the first one, since (j.elm->>'color')
extracts an array, while (j.elm->>'vehicle_type')
does simple string pieces.第一个运算符,因为(j.elm->>'color')
提取数组,而(j.elm->>'vehicle_type')
) 提取简单的字符串片段。
Therefore a regular expression is not needed such as below queries:因此不需要正则表达式,例如以下查询:
SELECT e.*
FROM example e
CROSS JOIN jsonb_array_elements(jsonTest->'vehicle') j(elm)
WHERE (j.elm->>'color')::jsonb ? 'Blue'
and和
SELECT e.*
FROM example e
CROSS JOIN jsonb_array_elements(jsonTest->'vehicle') j(elm)
WHERE (j.elm->>'vehicle_type') = 'SUV'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.