Hive两表三关联条件查询避免笛卡尔积告警方案咨询
解决方案
原有SQL使用OR作为JOIN关联条件,Hive无法判定关联的唯一性,会判定存在笛卡尔积风险,触发安全策略告警。可通过以下两种方案实现需求,均不会触发笛卡尔积告警:
方案一:列转行后等值关联(推荐)
先通过explode函数将table2的三个关联key拆分为多行,再和table1做等值左连接即可:
select t1.securitykey, t2.sector, t2.industrysubgroup from table1 t1 left join ( select explode(array(key1, key2, key3)) as join_key, sector, industrysubgroup from table2 ) t2 on t1.securitykey = t2.join_key;
如果存在同一个securitykey匹配到多条table2记录的场景,可根据业务需求加distinct或者聚合逻辑去重。
方案二:多次左连接取非空值
分别关联三个key,再通过coalesce函数取第一个非空的匹配结果:
select t1.securitykey, coalesce(k1.sector, k2.sector, k3.sector) as sector, coalesce(k1.industrysubgroup, k2.industrysubgroup, k3.industrysubgroup) as industrysubgroup from table1 t1 left join table2 k1 on t1.securitykey = k1.key1 left join table2 k2 on t1.securitykey = k2.key2 left join table2 k3 on t1.securitykey = k3.key3;
预期输出结果
按照给出的示例数据,两种方案最终输出结果一致,如下:
| securitykey | sector | industrysubgroup |
|---|---|---|
| 1 | Electronics | US electronincs |
| 2 | Industrial | Defense |
| 3 | Consumer | entertainment |
| 4 | NULL | NULL |
内容的提问来源于stack exchange,提问作者blackhole
相关产品推荐
相关产品推荐

