【发布时间】:2019-05-13 15:40:58
【问题描述】:
假设我们有以下 JSON 对象:
{"key_to_array":[{"key1":"value1","key2":{"var123":{"xyz":"I_need_version_1"}}},{"key1":"value1","key2":{"htg":{"uy1":"I_need_version_2"}}}]}}
插入表格:
drop table if exists modeling.modeling.pl_nested_json_array;
select '{"key_to_array":[{"key1":"value1","key2":{"var123":{"xyz":"I_need_version_1"}}},{"key1":"value1","key2":{"htg":{"uy1":"I_need_version_2"}}}]}' as json_data
into modeling.modeling.pl_nested_json_array
from modeling.modeling.some_other_table
limit 1;
为了到达I_need_version_*,我必须以半固定的方式行驶。 'Semi' 表示某些元素是变化的(键:var123、xyz、htg、uy1)。它们的组合数量有限,因此我可以通过在我的代码中编写不同的方式来处理它们,例如:
json_array_elements(cast(json_data as json) -> 'key_to_array') -> 'key2' -> 'var123' ->> 'xyz' as col1
问题是我目前的做法:
/* many columns version - unwanted */
select
json_array_elements(cast(json_data as json) -> 'key_to_array') ->> 'key1' as key1,
json_array_elements(cast(json_data as json) -> 'key_to_array') -> 'key2' -> 'var123' ->> 'xyz' as col1,
json_array_elements(cast(json_data as json) -> 'key_to_array') -> 'key2' -> 'htg' ->> 'uy1' as col2
from modeling.modeling.pl_nested_json_array;
生成与到达I_need_version_* 的方法一样多的列。因为对于每个JSON_data,只有一种方法是有效的(产生I_need_version_*)其余列col* 为NULL,我决定使用COALESCE() 来获得一列col 具有非NULL 值:
select
json_array_elements(cast(json_data as json) -> 'key_to_array') ->> 'key1' as key1,
coalesce(
json_array_elements(cast(json_data as json) -> 'key_to_array') -> 'key2' -> 'var123' ->> 'xyz',
json_array_elements(cast(json_data as json) -> 'key_to_array') -> 'key2' -> 'htg' ->> 'uy1') as col
from modeling.modeling.pl_nested_json_array;
执行此查询后,我得到ERROR: set-returning functions are not allowed in COALESCE。
我目前得到的输出:
key1 col1 col2
value1 I_need_version_1 [NULL]
value1 [NULL] I_need_version_2
我想得到什么:
key1 col
value1 I_need_version_1
value1 I_need_version_2
【问题讨论】:
-
[总是]可以将 select 嵌套为派生查询并将第一个输出合并到第二个输出:
SELECT COALESCE(t.col1, t.col2) FROM (SELECT .. FROM table ..) t。 -
也就是说,“正确”的方法可能是确保提供一个标量来合并..
-
感谢您的评论。我已经在我的最小可重现示例上测试了您的解决方案并且它有效。问题(或者说不便)是原始表
t有很多列。如果您的解决方案是我愿意使用的唯一可行的解决方案,但也欢迎直接处理问题的其他解决方案:)
标签: arrays json postgresql coalesce