记两则需求SQL关联注意事项
需求一: 两个表分条件选择join
两个表字段如下
表ci:
c_id | level 1 | level2 | level3 | level4 | 其他字段 |
---|---|---|---|---|---|
表qq:
level_rank | level_id | 其他字段 |
---|---|---|
两个表的关联条件是: qq.level_rank = 1 时, 用qq.level_id =ci. level1 ;qq.level_rank = 2 时, 用qq.level_id =ci. level2; qq.level_rank = 3 时, 用qq.level_id =ci. level3; qq.level_rank = 4 时, 用qq.level_id =ci. level4;
1.在 mysql gp gp impala 数据库中 可以如下形式join, 在on 后面写case 条件.
select *
from
(select 111 as level_1 ,111 as level_2 ,111 as level_3,111 as level_4
union all select 122 as level_1 ,122 as level_2 ,122 as level_3,122 as level_4
union all select 333 as level_1 ,331 as level_2 ,333 as level_3,333 as level_4
union all select 111 as level_1 ,111 as level_2 ,111 as level_3,444 as level_4) ci
left join
(select 1 as level_rank,111 as level_id
union all select 2 as level_rank ,222 as level_id
union all select 3 as level_rank ,333 as level_id
union all select 4 as level_rank ,44 as level_id) qq
on case qq.level_rank when 1 then qq.