我刚刚升级到 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
函数默认返回包含key
和value
列名称的行集。
但是,我希望json_each_text
返回自定义列名称,例如key1
和key2
:
-----------------------------------------------------------------------------------------
| id | first_name | last_name | education | key1 | value1 |
---- ------------ ----------- ---------------------------------------- -------- ---------
| 2 | John | Reese | {\"school\":\"NYSU\",\"state\":\"NY\"} | school | NYSU |
-----------------------------------------------------------------------------------------
在应用这些功能后,有没有办法获得不同的列名,例如&#39; key1&#39; 和&#39; value1&#39; ?< / p>
答案 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)