[英]Postgres query json array to find the count which matches the condition
我的 Postgres 12 DB 中有一个表my_table
其中包含一个列名itinerary
。
select column_name, data_type from information_schema.columns where table_name = 'my_table' and column_name = 'itinerary';
column_name | data_type
-------------+-----------
itinerary | ARRAY
(1 row)
行程中的每个元素都是一个带有字段名称address
的 JSON,它具有字段名称city
。 我可以使用以下查询找到与itinerary
的第一个元素的条件匹配的计数:
select count(*) from my_table where lower(itinerary[1]->'address'->>'city') = 'oakland';
count
-------
12
(1 row)
我还可以使用以下查询找到数组的长度:
select array_length(itinerary, 1) from my_table limit 1;
我想在他们的行程中找到所有可以有城市名称Oakland
的记录,而不仅仅是作为第一站。 我不知道如何弄清楚。 提前致谢。
您可以使用exists
和unnest()
:
select count(*)
from mytable t
where exists (
select 1
from unnest(t.itinerary) as x(obj)
where x.obj -> 'address'->>'city' = 'oakland'
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.