cast( NULL as struct<...>) 是不可能的,因为cast 仅适用于原始类型。
这里的技巧是使用 join 与包含所需类型结构的单行虚拟表。永远不应该满足连接条件,如果从连接的虚拟表中选择,它将返回与结构类型兼容的 NULL(数据类型将从虚拟表中获取,值将是 NULL,因为它没有连接)。
演示:
with
--your two tables, use real tables instead of CTEs
tab1 as (select 1 as id, 'John' as name, 'Some description' as description),
tab2 as (select 2 as id1),
--dummy table for struct<name:string, description:string> type generation
dummy as (select -9999999 as id, named_struct('name','x','description','x') as dummystruct )
select id,named_struct('name',name,'description',description),1 from tab1
union all
select id1, d.dummystruct,0
from tab2 t2
left join dummy d on t2.id1=d.id --you can use just false as a condition
;
结果:
1 {"name":"John","description":"Some description"} 1
2 NULL 0
只需将我的示例中的两个 CTE(tab1 和 tab2)替换为您的真实表格即可。
与解决方法非常相似的问题如何使array<struct>为空:https://*.com/a/65373624/2700344