json_each和json_each_text结果具有不同的列名

时间:2013-05-20 13:38:30

标签: postgresql

我刚刚升级到 Postgresql 9.3beta 。当我将 json_each json_each_text 函数应用于json列时,结果是一组列名为' key' 和'值'

以下是一个例子:

我有一个名为customers的表格,而education列的类型为json

客户表格如下:

 ----------------------------------------------------------------------
| id | first_name | last_name | education                              |
 ---- ------------ ----------- ----------------------------------------
| 1  | Harold     | Finch     | {\"school\":\"KSU\",\"state\":\"KS\"}  |
 ----------------------------------------------------------------------
| 2  | John       | Reese     | {\"school\":\"NYSU\",\"state\":\"NY\"} |
 ----------------------------------------------------------------------

查询

select * from customers, json_each_text(customers.education) where value = 'NYSU'

返回一组具有以下列名称的行

 ---------------------------------------------------------------------------------------
| id | first_name | last_name | education                              | key    | value |
 ---- ------------ ----------- ---------------------------------------- -------- -------
| 2  | John       | Reese     | {\"school\":\"NYSU\",\"state\":\"NY\"} | school | NYSU  |
 ---------------------------------------------------------------------------------------

因为json_each_text函数默认返回包含keyvalue列名称的行集。

但是,我希望json_each_text返回自定义列名称,例如key1key2

 -----------------------------------------------------------------------------------------
| id | first_name | last_name | education                              | key1    | value1 |
 ---- ------------ ----------- ---------------------------------------- -------- ---------
| 2  | John       | Reese     | {\"school\":\"NYSU\",\"state\":\"NY\"} | school  | NYSU   |
 -----------------------------------------------------------------------------------------

在应用这些功能后,有没有办法获得不同的列名,例如&#39; key1&#39; &#39; value1&#39; ?< / p>

1 个答案:

答案 0 :(得分:25)

您可以通过在FROM和SELECT子句中使用AS来解决这个问题:

postgres=# SELECT json_data.key AS key1,
                  json_data.value AS value1
           FROM customers, 
                json_each_text(customers.education) AS json_data
           WHERE value = 'NYSU';
  key1  | value1 
--------+--------
 school | NYSU
(1 row)