【问题标题】:Get json element from JSON Array从 JSON 数组中获取 json 元素
【发布时间】:2021-05-13 13:51:47
【问题描述】:

我有如下所示的示例数据:

表:

create table tbl_jdata
(
id int,
jdata json
);

insert into tbl_jdata values(1,'[{"salary":10000,"name":"mak"},{"salary":20000,"name":"jak"},{"salary":45000,"name":"abc"}]');

我只想显示一个薪水最高的 json 元素,例如预期结果中所示。

预期结果

id    jdata
-------------------------------------
1     [{"salary":45000,"name":"abc"}]

我的尝试

select t.id,each_section
from tbl_jdata t
cross join unnest(t.jdata) each_section
where t.id = 1 and (each_section ->> 'salary') in 
(
 select max(each_section ->> 'salary')
 from tbl_jdata t
 cross join unnest(t.jdata) each_section
);

得到一个错误:

ERROR: function unnest(json) does not exist

【问题讨论】:

  • @a_horse_with_no_name,抱歉,jdata 列的实际数据类型是 json,并且数据已以给定格式存储。

标签: postgresql postgresql-11


【解决方案1】:

您需要在 JSON 数组上使用 json_array_elements() 而不是 unnest()。之后,您可以使用横向连接来获取最高元素:

select t.id, i.*
from the_table t
  cross join lateral (
     select x.item
     from json_array_elements(t.jdata) as x(item)
     order by (x.item ->> 'salary')::int desc
     limit 1
   ) i

请注意,建议使用jsonb 而不是json

【讨论】:

    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-29
      • 2019-08-15
      • 1970-01-01
      • 2014-10-14
      • 1970-01-01
      • 2012-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多