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

标签 postgresql

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

这是一个例子:

我有一个名为 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   |
 -----------------------------------------------------------------------------------------

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

最佳答案

您可以通过在 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)

关于postgresql - json_each 和 json_each_text 结果具有不同的列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16650796/

相关文章:

sql - 是否可以进行递归 SQL 查询?

postgresql - Ebean 中的 Heroku Postgres bytea

node.js - 在我的前端和后端之间创建一个 webhook

oracle - 如何使用 ora2pg 迁移导出特定的表架构和数据?

sql - 运行用户定义的 SQL 脚本的 postgresql pgBench 工具

sql 计算连续零

postgresql - N字以内的全文搜索

sql连接表,没有提供完美的结果

python - 没有错误记录失败的 Postgres/Psycopg2 copy_from

sql - Postgres 连接所有