15

我刚刚升级到Postgresql 9.3beta。当我将json_eachjson_each_text函数应用于 json 列时,结果是一组列名为'key''value' 的行。

这是一个例子:

我有一个名为的表customerseducation列的类型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返回自定义列名,例如key1and key2

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

应用这些函数后,有没有办法获得不同的列名,如“key1”“value1” ?

4

1 回答 1

41

您可以通过在 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)
于 2013-05-20T22:54:36.740 回答