首页 > 解决方案 > 用于从其他表中查找数据的 SQL / Oracle SQL 代码

问题描述

如何编写查询以从其他表中获取现有表中每一列的数据。

请查找附表和示例数据要求的图片。

标签: sqloracle

解决方案


你可以left join三遍system_code

select
    d.id,
    s_cat.full_name cat_code_full_name,
    s_group.full_name group_code_full_name,
    s_other.full_name other_code_full_name
from data_table d 
left join system_code s_cat
    on s_cat.value = d.cat_code and s.code = 1
left join system_code s_group
    on s_group.value = d.group_code and s_group.code = 2
left join system_code s_other
    on s_other.value = d.other_code and s_other.code = 3

为了避免重复连接,另一种解决方案是进行条件聚合:

select
    d.id,
    max(case when s.value = d.cat_code   and s.code = 1 then s.full_name end) cat_code_full_name,
    max(case when s.value = d.group_code and s.code = 2 then s.full_name end) group_code_full_name,
    max(case when s.value = d.other_code and s.code = 3 then s.full_name end) other_code_full_name
from data_table d 
left join system_code s on s.value in (d.cat_code, d.group_code, d.other_code)
gtoup by d.id

推荐阅读