个人随笔
目录
MySQL查询所有子级或者父级的方法:冗余法和递归法
2024-06-28 17:05:48

假设我们有一个机构表(inst_info),字段为ID(id),机构号(inst_code),机构名字(inst_name),父级机构号(parent_inst_code).

现在可能面临两种需求,第一种,给定一个机构号,查询所有子级机构,包括子级的子级。怎么做呢!

方案1、字段冗余法

我们可以在这个表多加几个字段,把每一个机构的所有父级机构都冗余,比如机构是省市县网点,那么表加上六个字段

  1. 县级机构号(county_inst_code),
  2. 县级机构名称(county_inst_name),
  3. 市级机构号(city_inst_code),
  4. 市级机构名称(city_inst_name),
  5. 省级机构号(province_inst_code),
  6. 省级机构名称(province_inst_name

查子级

这样的话,查询所有子级,根据所传机构层级,那么sql就变为

  1. #市
  2. select * from inst_info where city_inst_code = #{city_inst_code}
  3. #省
  4. select * from inst_info where province_inst_code = #{province_inst_code}
  5. #县
  6. select * from inst_info where county_inst_code = #{county_inst_code}

用空间换时间。

查父级

查父级就更简单,当前这条记录就有全部父级机构的信息。

递归法

查子级

当然,如果我们不想要多字段,难以维护,那么我们可以用RECURSIVE递归查询,如果我们是查询子级,用向下递归

  1. with RECURSIVE dept as (
  2. select * from inst_info where inst_code=#{inst_code}
  3. UNION all
  4. select b.* from dept a inner join inst_info b on a.inst_code=b.parent_inst_code
  5. )
  6. select * from dept;

查父级

刚好相反即可

  1. with RECURSIVE dept as (
  2. select * from inst_info where inst_code=#{inst_code}
  3. UNION all
  4. select b.* from dept a inner join inst_info b on a.parent_inst_code=b.inst_code
  5. )
  6. select * from dept;
 23

啊!这个可能是世界上最丑的留言输入框功能~


当然,也是最丑的留言列表

有疑问发邮件到 : suibibk@qq.com 侵权立删
Copyright : 个人随笔   备案号 : 粤ICP备18099399号-2