简体   繁体   中英

PostgreSQL: query on JSONB data

I have a table storing data as below:

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": []}

I have the following JSON file:

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

I would like to display the different dates associated with the id column in a table, and to ignore rows with no date available (row 4 is not displayed in the result):

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

Here the query I have written but it returns nothing:

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

FROM myTable

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

尝试这个:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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