我刚刚升级到Postgresql 9.3beta.当我将json_each或json_each_text函数应用于json列时,结果是一组列名为'key'和'value'的行.
这是一个例子:
我有一个名为table的表customers
,education
列是类型json
客户表如下:
----------------------------------------------------------------------
| id | first_name | last_name | education |
---- ------------ ----------- ----------------------------------------
| 1 | Harold | Finch | {\"school\":\"KSU\",\"state\":\"KS\"} |
----------------------------------------------------------------------
| 2 | John | Reese | {\"school\":\"NYSU\",\"state\":\"NY\"} |
----------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)
查询
select * from customers, json_each_text(customers.education) where value = 'NYSU'
Run Code Online (Sandbox Code Playgroud)
返回一组具有以下列名称的行
---------------------------------------------------------------------------------------
| id | first_name | last_name | education | key | value |
---- ------------ ----------- ---------------------------------------- -------- -------
| 2 | John | Reese | {\"school\":\"NYSU\",\"state\":\"NY\"} | school | NYSU |
---------------------------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)
因为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 |
-----------------------------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)
有没有办法在应用这些函数后获得不同的列名,如'key1'和'value1'?
小智 29
您可以通过在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)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13975 次 |
最近记录: |