简体   繁体   English

Postgres获取搜索并向每行获取多个数组json

[英]Postgres get search and get multiple array json to each row

I wants to get all subscriptions with interval "1 WEEK" from the following 'data' column 我想从以下“数据”列中获取所有间隔为“ 1周”的订阅

[
  {
    "id": "tran_6ac25129951962e99f28fa488993",
    "amount": 1200,
    "client": {
      "id": "client_622bdf4cce2351f28243",
      "subscription": [
        {
          "id": "sub_a67d59efb2bcbf73485a",
          "amount": 3900,
          "currency": "USD",
          "interval": "1 WEEK"
        },
        {
          "id": "sub_a67d59efb2bcbf73485a",
          "amount": 3900,
          "currency": "USD",
          "interval": "1 WEEK"
        }
      ]
    },
    "currency": "USD"
  },
  {
    "id": "tran_xxxxxxx",
    "amount": 1200,
    "client": {
      "id": "client_xxxxxx8243",
      "subscription": [
        {
          "id": "sub_xxefb2bcbf73485a",
          "amount": 3900,
          "currency": "USD",
          "interval": "1 Year"
        },
        {
          "id": "sub_yyyyyb2bcbf73485a",
          "amount": 3900,
          "currency": "USD",
          "interval": "1 WEEK"
        }
      ]
    },
    "currency": "USD"
  }
]

My table structure: 我的表结构:

CREATE TABLE transactions
(
  data json,
  id bigserial NOT NULL,
  created_date time without time zone,
  CONSTRAINT transactions_pkey PRIMARY KEY (id)
)

In output I wants to get all "1 WEEk" subscription as rows. 在输出中,我希望将所有的“ 1 WEEk”订阅获取为行。 Above data should give 3 rows 以上数据应给出3行

I am using Postgres 9.3+ 我正在使用Postgres 9.3+

Its a nested query and I have tried writing it in as readable form as I can. 它是一个嵌套查询,我尝试过以可读形式编写它。 I hope you can understand it - 希望您能理解-

select subscriptions from
(
    select
        cast
        (
            json_array_elements
            (
                json_array_elements(data)->'client'->'subscription'
            )
            as text
        )
        as subscriptions,

        json_array_elements
        (
            json_array_elements(data)->'client'->'subscription'
        )
        ->>'interval'
        as intervals

    from
        transactions
)
as 
    xyz
where
     intervals = '1 WEEK';

For information regarding these functions, you can refer to - http://www.postgresql.org/docs/9.3/static/functions-json.html 有关这些功能的信息,您可以参考-http: //www.postgresql.org/docs/9.3/static/functions-json.html

Edit:- 编辑:-

As per performance requirements, I guess this will work better than the previous one - 根据性能要求,我想这会比上一个更好-

select * from (
  select cast (
    json_array_elements (
      json_array_elements(data)->'client'->'subscription'
    ) as text
  ) as subscription from transactions
) as temp
where subscription LIKE '%"interval":"1 WEEK"%';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM