PostgreSQL JSON - 嵌套列表的子集

PostgreSQL JSON - Subset of nested lists

我在 PostgreSQL 数据库中有一列,它基本上是 json 化的 python 元组列表:

[
  ["Mobile","111-111-1111"],
  ["Office","222-222-2222"],
  ["Mobile","333-333-3333"],
  ["Fax","444-444-4444"],
]

我想构建一个查询,该查询 return 是基于每个嵌套列表中的第一个值的列表的子集。下面是一个伪查询,希望能说明我所追求的:

SELECT
  foo AS bar,
  (SELECT 
     element 
   FROM 
     phone_numbers 
   WHERE
     element::json->>0 = "Mobile") AS mobile_numbers
FROM
  db
;

mobile_numbers == [["Mobile","111-111-1111"],["Mobile","333-333-3333"]]

我只知道 PostgreSQL 中的 json 运算符(以及一般的 SQL 查询),主要是在字典方面。我可以在这里找到许多关于如何深入研究嵌套字典和 return 一个值的示例,但我还没有找到任何与我所追求的完全匹配的东西。

感谢您的帮助。

假设该列包含有效的 json 作为数组的数组,您应该使用 jsonb_array_elements(), filter inner arrays (tuples) by the first (index 0) their elements and aggregate results with jsonb_agg().

取消嵌套外部数组
with my_table(phone_numbers) as (
values
('[
  ["Mobile","111-111-1111"],
  ["Office","222-222-2222"],
  ["Mobile","333-333-3333"],
  ["Fax","444-444-4444"]
]'::jsonb)
)

select jsonb_agg(phone)
from my_table
cross join jsonb_array_elements(phone_numbers) as arr(phone)
where phone->>0 = 'Mobile'

                        jsonb_agg                         
----------------------------------------------------------
 [["Mobile", "111-111-1111"], ["Mobile", "333-333-3333"]]
(1 row)