如何从jsonb列中提取数据

ux6nzvsh  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(441)

我们在vehicle表中有一个以jsonb格式存储的车辆信息。

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'
brtdzjyr

brtdzjyr1#

如果我没记错的话,你可以用 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'

db小提琴演示:

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

相关问题