gpt4 book ai didi

sql - 如何从 JSONB 列中提取数据

转载 作者:行者123 更新时间:2023-12-04 15:25:08 24 4
gpt4 key购买 nike

我们在 vehicle 表中以 JSONB 格式存储了一个 vehicle_info。

id |                                     vehicle_info(JSONB)                                     
----+------------------------------------------------------------------------------------
1 | {"milestone": {"Honda_car": {"status":"sold"}}
3 | {"milestone": {"Mitsubishi_car", {"status":"available"}}
2 | {"milestone": {"Honda_car", {"status":"available"}}

如何提取后缀为car的数据。下面是我能想到但最终出错的。

select * from vehicle where milestone -> LIKE '%_car' ->>'status'

最佳答案

如果我没听错,您可以使用 jsonb_object_keys() 枚举键,然后过滤那些以 '_car' 结尾的键,最后提取值:

select t.*, t.vehicle_info -> 'milestone' -> k.val ->> 'status' status
from mytable t
cross join lateral jsonb_object_keys(t.vehicle_info -> 'milestone') as k(val)
where k.val like '%_car'

Demo on DB Fiddle :

id | vehicle_info                                               | status   -: | :--------------------------------------------------------- | :-------- 1 | {"milestone": {"Honda_car": {"status": "sold"}}}           | sold      3 | {"milestone": {"Mitsubishi_car": {"status": "available"}}} | available 2 | {"milestone": {"Honda_car": {"status": "available"}}}      | available

关于sql - 如何从 JSONB 列中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62439653/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com