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
    
    
  • 相关阅读:
    linux 防火墙管理
    自动化运维监控工具有哪些?常用的开源运维监控工具大全
    编程必备github代码仓库使用
    安全加密算法
    浅笑若风之高效工作流程
    jmeter压力测试工具使用
    ES扩容实战记录
    在5G+AI+CLCP下拉动互联网走向物联网
    设计模式之简单工厂模式
    设计模式之单例模式
  • 原文地址:https://www.cnblogs.com/yingjiang/p/4749290.html
Copyright © 2011-2022 走看看