在postgresql中以单独的行和列插入json数据并将其插入(10.3)

时间:2018-06-09 11:17:37

标签: postgresql postgresql-10

我有以下数据集:

{"date":{"year":2017,"month":7,"day":2},"data":{"param1":[10,20,30,440],"param2":[55,65,75,85],"param3":[43,55,71,72]}}

我从名为rawData的表中检索数据。

现在我想要删除数组中的值,并将它们放在另一个表(seperateData)中的4个单独的行和列中,因此对于此示例,它看起来像:

year  | month | day | param1 | param2 | param3

2017      7      2      10       55       43
2017      7      2      20       65       55
2017      7      2      30       75       71
2017      7      2      440      85       72

我猜我必须使用不正确和正常来实现这一点,但我仍然坚持我应该如何继续。数组param1,param2,param3的长度始终相同。

我已经对这些数据做了一个小提琴: https://www.db-fiddle.com/f/jZhYLEvdSERzLCDyoAJz65/0

1 个答案:

答案 0 :(得分:1)

正确的做法不是最好的方法我的PostgreSQL体验并不是那么好但它有效。

<强>查询

  SELECT   
      ((rawData.values)::json->'date')::json->'year' AS year
    , ((rawData.values)::json->'date')::json->'month' AS month
    , ((rawData.values)::json->'date')::json->'day' AS day  
    , JSON_ARRAY_ELEMENTS(((rawData.values)::json->'data')::json->'param1') AS param1
    , JSON_ARRAY_ELEMENTS(((rawData.values)::json->'data')::json->'param2') AS param2   
    , JSON_ARRAY_ELEMENTS(((rawData.values)::json->'data')::json->'param3') AS param3
  FROM
   rawData

demo https://www.db-fiddle.com/f/jZhYLEvdSERzLCDyoAJz65/1

当数组param1,param2,param3的长度不相等时,查询也会起作用。

demo https://www.db-fiddle.com/f/jZhYLEvdSERzLCDyoAJz65/4

  

感谢您的回答,它迄今为止有效。我唯一忘记的是,我   实际上也需要索引作为单独的列。所以索引了   数组元素。任何想法

这可能与GENERATE_SERIES结合使用JSON_ARRAY_LENGTH

<强>查询

  SELECT   
      ((rawData.values)::json->'date')::json->'year' AS year
    , ((rawData.values)::json->'date')::json->'month' AS month
    , ((rawData.values)::json->'date')::json->'day' AS day  
    , JSON_ARRAY_ELEMENTS(((rawData.values)::json->'data')::json->'param1') AS param1
    , GENERATE_SERIES(1, JSON_ARRAY_LENGTH(((rawData.values)::json->'data')::json->'param1')) AS param1_array_index
    , JSON_ARRAY_ELEMENTS(((rawData.values)::json->'data')::json->'param2') AS param2   
    , GENERATE_SERIES(1, JSON_ARRAY_LENGTH(((rawData.values)::json->'data')::json->'param2')) AS param2_array_index    
    , JSON_ARRAY_ELEMENTS(((rawData.values)::json->'data')::json->'param3') AS param3
    , GENERATE_SERIES(1, JSON_ARRAY_LENGTH(((rawData.values)::json->'data')::json->'param3')) AS param3_array_index        
  FROM
   rawData

参见演示https://www.db-fiddle.com/f/jZhYLEvdSERzLCDyoAJz65/6