2015-03-03 64 views
6

我在我的数据库有一个表中有一列包含json记录。使用json_populate_recordset而不创建表?

id | json_records 
---+------------- 
0 | "[{'x1' : 1234, 'x2' : 5678},{'x1' : 2345, 'x2' : 6789}]' 
1 | "[{'x1' : 4321, 'x2' : 8765},{'x1' : 5432, 'x2' : 9876}]' 

我希望得到的东西是这样的:

id | x1 | x2 
---+------+----- 
0 | 1234 | 5678 
0 | 2345 | 6789 
1 | 4321 | 8765 
1 | 5432 | 9876 

,但我有麻烦的查询工作:

select json_populate_recordset(json_records) from my_table 

我使用json_populate_recordset看到的几个例子将结果插入表中,但我只是想返回结果。有没有办法做到这一点,而不创建一个新表?

+0

你能指向任何其他好你找到的例子?我发现这个世界似乎对于在postgres中使用这些json操作的文档有点光。 – 2015-03-17 14:14:19

回答

6

你必须创建一个新的类型,传递给函数(注意,由于该json_populate返回json_type你必须使用(row).*号来获取各个字段):

CREATE type json_type AS (x1 int, x2 int); 

SELECT id, (json_populate_recordset(null::json_type, json_records)).* FROM my_table; 
相关问题