如何查找jsonArray元素之一的所有行赋予属性相等的属性?

时间:2014-09-01 11:07:00

标签: postgresql postgresql-9.3

在我的表中,我有json列media,它设置为数组(json数组),如下所示:

media: [
   {},
   {},
   {},
   ...,
   { key: 'thumbnail', metaData: { width: 123, height: 321 } }
]

我必须找到包含(在媒体列中)具有key = 'thumbnail' AND metaData.width = 123 AND metaData.height = 321属性的对象的所有行。

我如何使用Postgres 9.3做到这一点?

1 个答案:

答案 0 :(得分:1)

select id, a
from (
    select id, json_array_elements((j ->> 'media')::json) as a
    from (values(1, '
        {"media": [
           {},
           {},
           {},
           { "key": "thumbnail", "metaData": { "width": 123, "height": 321 } }
        ]}'::json
    )) s(id, j)
) s
where
    a ->> 'key' = 'thumbnail'
    and
    (a #>> '{metaData, width}')::integer = 123
    and
    (a #>> '{metaData, height}')::integer = 321
;
 id |                                  a                                  
----+---------------------------------------------------------------------
  1 | { "key": "thumbnail", "metaData": { "width": 123, "height": 321 } }