oracle及postgresql遞歸查詢

相信大家經常會遇到這樣的需求,通過一位職員的id/name獲取其下屬(包括非直屬)所有員工列表,用java實現這個功能相信也得花上一會功夫,但是如果是依賴數據庫來實現這個功能那就so easy了。先來看看Postgresql如何實現這樣的功能

WITH RECURSIVE r AS (SELECT * FROM t_account WHERE name = #{accountName} 
           union ALL 
          SELECT t_account.* FROM t_account, r WHERE t_account.parent = r.name 
        ) 
   SELECT * FROM r ORDER BY name

 

這樣是不是在代碼量上減輕了很多啊,具體見postgresql官方文檔http://www.postgresql.org/docs/8.4/static/queries-with.html
接着來看看oracle如何做遞歸查詢:
從ROOT往末端遍歷:

select * from t_account t start with t.parent is null connect by prior t.name=t.parent


從末端到ROOT端遍歷:select * from t_account t start with t.name='**' connect by t.parent=t.name
具體用法細節請參考oracle文檔
下面再參照java的實現:

public class JsonTreeGenerate<T extends AbstractTreeNode> {
 private Logger logger = Logger.getLogger(JsonTreeGenerate.class);
 private Lock lock = new ReentrantLock();
 private Set<T> set = new HashSet<T>();
 
 public Set<T> getAllChild(Set<T> sets,T node){
  lock.lock();
  try {
   if(set.size()>0){
    set.clear();
   }
   recursionFn(sets,node);
  } catch (Exception e) {
   logger.error("", e);
  }finally{
   lock.unlock();
  }
  return set;
 }
 public void recursionFn(Set<T> sets , T node){
  set.add(node);
  if(hasChild(sets,node)){
         List<T> hashSet = getChildList(sets , node);
         Iterator<T> it = hashSet.iterator();
         while(it.hasNext()){    
          T n = (T)it.next();
          if(null==node.getChildren()){
           node.setChildren(new ArrayList<AbstractTreeNode>());
          }
          node.getChildren().add(n);
                recursionFn(sets,n);    
            } 
         //recursionFn(accountSet,node);
        } 
    }
 
 
 public List<T> getChildList(Set<T> list, T t){
  List<T> nodeList=new ArrayList<T>();
  Iterator<T> it = list.iterator();    
        while(it.hasNext()){    
         T accounts = it.next();    
            if(accounts.getParent()==t.getId()){    
             nodeList.add(accounts);
             //t.getChildren().add(accounts);
            }    
        }    
        return nodeList;  
 }
 public boolean hasChild(Set<T> list,T node){
  List<T> l =getChildList(list,node);
  if(null!=l&&l.size()>0){
   return true;
  }
  return false;
 }
}


 

這個一比較就知道前者處理該問題的簡潔性了吧,

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章