【问题标题】:Postgres query json array to find the count which matches the conditionPostgres 查询 json 数组以查找与条件匹配的计数
【发布时间】:2020-11-18 20:11:36
【问题描述】:

我的 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 的记录,而不仅仅是作为第一站。我不知道如何弄清楚。提前致谢。

【问题讨论】:

    标签: sql arrays json postgresql postgresql-12


    【解决方案1】:

    您可以使用existsunnest()

    select count(*)
    from mytable t
    where exists (
        select 1
        from unnest(t.itinerary) as x(obj)
        where x.obj -> 'address'->>'city' = 'oakland'
    )
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-06
    • 2017-07-20
    • 2016-06-05
    • 2021-08-07
    • 1970-01-01
    • 2012-06-24
    • 2013-09-20
    • 1970-01-01
    相关资源
    最近更新 更多