文库

PG递归查询

PG递归查询

八月 20, 2018 阅读 5283 字数 596 喜欢 1

distinct xxcount(distinct xx)的递归优化方法

 

当数据量大,count(distinct xx)结果会很慢,distinct结果数量较少时,可以使用递归方法优化。distinct结果多不适用。

 

如查询记录有多少家企业,查询速度比起count(distinct xx)快很多

 

with recursive skip as (  

  (  

    select min(t.code) as code from table t where t.code is not null  

  )  

  union all  

  (  

    select (select min(t.code) from table t where t.code> s.code and t.code is not null)   

      from skip s where s.code is not null  

  )  -- 这里的where s.code is not null 一定要加,否则就死循环了.  

)   

select count(code) from skip;  

 

 

 

参考

https://yq.aliyun.com/articles/39689

https://blog.csdn.net/wickedvalley/article/details/70717328















粤ICP备18103437号