Oracle查询优化之减少统计的数据量
统计各部门人数很简单,通过部门分组即可,要统计部门以下下级部门的人数也简单,通过递归。要统计所有有下级部门的部门人数(包含下级)页比较简单,
先查询出有下级的部门,在对每个部门进行递归查询,如下:
select count(1) s ,b.b0200 from a01 a, (select b0200 from b02 d where b0209=5 start with d.b0200=1 connect by prior d.b0200=d.b0203) b /*查询工会id为1的所有有下级的工会*/ where a.b0200 in (select b0200 from b02 d start with d.b0200=1 connect by prior d.b0200=d.b0203) group by b.b0200
这个方法是最简单的,逻辑也很清楚,不过结果就不好了,简单的来说效率太低。300多万条数据执行时间已经难以想象了。
只有进行改进,减少数据量,一开始从上级开始统计数据量很大,那么就从下级开始统计减少数据量。即先统计最下级工会的第一个上级的人数,依次往上累加,这样的数据量就少了很多
select b.b0200, sum(s) from ( select b.b0203 as b0200,count(1) s from a01 a,(select b0200 ,b0203 from b02 b where b0209=0 start with b.b0200=1 connect by prior b.b0200=b.b0203) b where a.b0200=b.b0200 group by b.b0203) a,(select b0200 from b02 d where b0209=5 start with d.b0200=1 connect by prior d.b0200=d.b0203) b/*查询工会id为1的所有有下级的工会*/ where a.b0200 in ( select b0200 from b02 c start with c.b0200=b.b0200 connect by prior c.b0200=c.b0203 ) group by b.b0200
此时的效果已经比上一次好了很多,花费15秒左右的时间
https://snailsdream.github.io/