假设我们有一个机构表(inst_info),字段为ID(id),机构号(inst_code),机构名字(inst_name),父级机构号(parent_inst_code).
现在可能面临两种需求,第一种,给定一个机构号,查询所有子级机构,包括子级的子级。怎么做呢!
方案1、字段冗余法
我们可以在这个表多加几个字段,把每一个机构的所有父级机构都冗余,比如机构是省市县网点,那么表加上六个字段
县级机构号(county_inst_code),
县级机构名称(county_inst_name),
市级机构号(city_inst_code),
市级机构名称(city_inst_name),
省级机构号(province_inst_code),
省级机构名称(province_inst_name)
查子级
这样的话,查询所有子级,根据所传机构层级,那么sql就变为
#市
select * from inst_info where city_inst_code = #{city_inst_code}
#省
select * from inst_info where province_inst_code = #{province_inst_code}
#县
select * from inst_info where county_inst_code = #{county_inst_code}
用空间换时间。
查父级
查父级就更简单,当前这条记录就有全部父级机构的信息。
递归法
查子级
当然,如果我们不想要多字段,难以维护,那么我们可以用RECURSIVE递归查询,如果我们是查询子级,用向下递归
with RECURSIVE dept as (
select * from inst_info where inst_code=#{inst_code}
UNION all
select b.* from dept a inner join inst_info b on a.inst_code=b.parent_inst_code
)
select * from dept;
查父级
刚好相反即可
with RECURSIVE dept as (
select * from inst_info where inst_code=#{inst_code}
UNION all
select b.* from dept a inner join inst_info b on a.parent_inst_code=b.inst_code
)
select * from dept;