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

时间:2015-03-16 02:03:59

标签: json postgresql

我希望获得所有订阅的间隔时间" 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"
  }
]

我的表结构:

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

在输出中我希望得到所有" 1 WEEk"订阅为行。以上数据应该给出3行

我正在使用Postgres 9.3 +

1 个答案:

答案 0 :(得分:1)

它是一个嵌套查询,我尝试以尽可能可读的形式编写它。我希望你能理解它 -

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';

有关这些功能的信息,请参阅 - http://www.postgresql.org/docs/9.3/static/functions-json.html

编辑: -

根据性能要求,我猜这会比前一个更好 -

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"%';