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
    
    
  • 相关阅读:
    Windows程序调试系列: 使用VC++生成调试信息 转
    mysql基础
    mysql bug
    VS2010下配置Winpcap 开发环境
    WIN7 下面 装XP
    Iptables 指南 1.1.19
    mysql内核 innodb存储引警(卷1)配书 用VS 2003 编绎 mysql-3.23.49 源代码
    cmake
    Windows+VS2012环境下编译调试MySQL源码 转
    哈佛图书馆自习室墙上的训言 (自勉)
  • 原文地址:https://www.cnblogs.com/yingjiang/p/4749290.html
Copyright © 2011-2022 走看看