[英]Postgres query json array to find the count which matches the condition
I have a table my_table
with a column name itinerary
in my Postgres 12 DB.我的 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)
Every element in the itinerary is a JSON with the field name address
, which has the field name city
.行程中的每个元素都是一个带有字段名称
address
的 JSON,它具有字段名称city
。 I can find the count which matches the condition for the first element of the itinerary
by using the following query:我可以使用以下查询找到与
itinerary
的第一个元素的条件匹配的计数:
select count(*) from my_table where lower(itinerary[1]->'address'->>'city') = 'oakland';
count
-------
12
(1 row)
and I can also find the length of an array by using the following query:我还可以使用以下查询找到数组的长度:
select array_length(itinerary, 1) from my_table limit 1;
I would like to find all the records which can have a city name Oakland
in their itinerary, not only as a first stop.我想在他们的行程中找到所有可以有城市名称
Oakland
的记录,而不仅仅是作为第一站。 I am not sure how to figure out that.我不知道如何弄清楚。 Thanks in advance.
提前致谢。
You can use exists
and unnest()
:您可以使用
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.