选择具有最大JSON密钥的对象

时间:2017-05-08 19:10:13

标签: sql json postgresql

给定一个名为test的表,其定义如下

 Column | Type | Modifiers
--------+------+-----------
 a      | json |

其中每一行都有一些类似于

的形式的JSON
{
  "1": "abc",
  "2": "def",
  "3": "ghi" 
}

如何进行选择具有最大键值的查询? (在此示例中,您选择"ghi",因为它是关键,3,是最大的)

我将它概念化的方式,理想情况下它是这样的查询:

SELECT a->max(json_object_keys(a)) from test;

但显然这不起作用。这可能吗?

2 个答案:

答案 0 :(得分:1)

您可以使用json_each这样做:

select   value 
from     (  select (json_each(a)).* 
            from   test
         ) keyval
order by key::int desc
limit    1;

rextester.com

上查看它

答案 1 :(得分:1)

让我们尝试逐步解决问题:

tometzky=> select * from json_object_keys('{"1": "abc","2": "def","3": "ghi"}'::json) as k;
 k 
---
 1
 2
 3
(3 rows)

tometzky=> select max(k) from json_object_keys('{"1": "abc","2": "def","3": "ghi"}'::json) as k;
 max 
-----
 3
(1 row)

tometzky=> create temporary table test (a json);
tometzky=> insert into test values('{
  "1": "abc",
  "2": "def",
  "3": "ghi" 
}');
tometzky=> insert into test values('{
  "100": "jkl",
  "20": "kmo",
  "3": "pqr" 
}');

tometzky=> select (select max(k) from json_object_keys(a) as k) from test;
 max 
-----
 3
 3
(2 rows)

tometzky=> select (select max(k::int) from json_object_keys(a) as k) from test;
 max 
-----
   3
 100
(2 rows)

所以答案是:

tometzky=> select a->(select max(k::int)::text from json_object_keys(a) as k) from test;
 ?column? 
----------
 "ghi"
 "jkl"
(2 rows)

我认为“具有最大键的值”是针对每一行,因为它看起来不像一个明确定义的问题。