PostgreSQL:查询JSONB数据

时间:2016-05-24 14:34:30

标签: json postgresql nosql

我有一个存储数据的表格如下:

id       | data
serial   | jsonb 
---------+-----------------------------------------------
1        | {"files": [{"date": "2016-05-20", "name": "a"},{"date": "2016-05-21", "name": "b"}]}
2        | {"files": [{"date": "2015-04-02", "name": "c"}]}
3        | {"files": [{"date": "2016-02-12", "name": "d"},{"date": "2016-01-27", "name": "e"}]}
4        | {"files": []}

我有以下JSON文件:

{
  "files": [
    {"date": "2016-05-20", "name": "Test 1"},
    {"date": "2016-05-21", "name": "Test 2"},
    {"date": "2016-05-22", "name": "Test 3"}
  ]
}

我想在表格中显示与id列关联的不同日期,并忽略没有可用日期的行(结果中不显示第4行):

id  | date
----+-----------
1   | 2016-05-20
1   | 2016-05-21
2   | 2015-04-02
3   | 2016-02-12
3   | 2016-01-27

这里是我写过的查询,但它什么也没有返回:

SELECT 
  id,
  "data" -> 'files' ->> 'date' AS "date" 

FROM myTable

WHERE "data" -> 'files' @> '{"date"}'::jsonb ;

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT id, json_array_elements((data->'files')::json)->>'date' as "date" FROM myTable