zoukankan      html  css  js  c++  java
  • mysql实现ORACLE的connect by prior父子递归查询

    oracle中有connect by prior ,可以实现父子递归查询。而mysql中没有这种功能,但我们可以变通实现。

     比如一个表:

    Table Name: tb_Tree
    
    Id | ParentId | Name
    --------------------
    1  | 0        | Fruits
    2  | 0        | Vegetables
    3  | 1        | Apple
    4  | 1        | Orange
    5  | 2        | Cabbage
    6  | 2        | Eggplant

    我们需要知道某个ID的所有下级。

    以下这个查询,可以列出所有水果蔬菜的四层上级ID,如果没有四级,则相应的parentid为Null。(你也可以扩展级数)

    select id,name,parentid 
    ,(select parentid from tb_tree where id=t.parentid) parentid2 
    ,(select parentid from tb_tree where id=(select parentid from tb_tree where id=t.parentid)) parentid3 
    ,(select parentid from tb_tree where id=(select parentid from tb_tree where id=(select parentid from tb_tree where id=t.parentid))) parentid4 
    from tb_tree t 

    于是我们很方便查到我们所要的结果,比如要查fruits的所有children:
    select id ,name from (
            select id, name, parentid
            ,(select parentid from tb_tree where id=t.parentid) parentid2
            ,(select parentid from tb_tree where id=(select parentid from tb_tree where id=t.parentid)) parentid3
            ,(select parentid from tb_tree where id=(select parentid from tb_tree where id=(select parentid from tb_tree where id=t.parentid))) parentid4 
            from tb_tree t) tt
        where ifnull(parentid4,0)=1 or ifnull(parentid3,0)=1 or ifnull(parentid2,0)=1 or ifnull(parentid,0)=1
    
    
  • 相关阅读:
    PP篇10 修改工单组件行
    取未清PO逻辑
    PP篇7 生产替代料齐套后处理
    PP篇9 更改计划订单
    DEBUG技巧里的问题1 双击某个变量不能显示
    HoloLens开发手记
    开始开发HoloLens应用吧 Start Developing HoloLens Apps Today
    HoloLens开发手记
    HoloLens开发手记
    HoloLens开发手记
  • 原文地址:https://www.cnblogs.com/yingjiang/p/4749290.html
Copyright © 2011-2022 走看看