使用json_populate_recordset而不创建表?

时间:2015-03-03 00:41:47

标签: sql json postgresql

我的数据库中有一个表,其中包含一个包含json记录的列。

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看到的几个例子将结果插入到表中,但我只是想返回结果。有没有办法在不创建新表的情况下执行此操作?

2 个答案:

答案 0 :(得分:10)

您必须创建一个新类型才能传递给该函数(请注意,当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;

答案 1 :(得分:0)

这是在PostgreSQL 11上使用json字符串的另一个示例

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState == null) {
      // Set the local night mode to some value
      getDelegate().setLocalNightMode(
                AppCompatDelegate.MODE_NIGHT_...);
      // Now recreate for it to take effect
      recreate();
    }
  }
}
相关问题