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

İlk*_*anç 10 postgresql

我刚刚升级到Postgresql 9.3beta.当我将json_eachjson_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函数默认返回带有列名keyvalue行名的行集.

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

 -----------------------------------------------------------------------------------------
| 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)

  • 不,只是感到惊讶,有效.如果没有LATERAL,您不应该在同一FROM子句中的另一个条目中引用一个表的列.Aaah,这就是它的工作原理:http://www.postgresql.org/message-id/E1TzD9T-0005bR-1H@gemulon.postgresql.org (9认同)
  • 值得一提的是,这使用了隐式横向连接。我很难理解这是如何运作的 (2认同)