create table test(
id int,
parent_id int
);
insert into test values(1,0);
insert into test values(2,0);
insert into test values(3,0);insert into test values(4,1);
insert into test values(5,2);
insert into test values(6,3);insert into test values(7,4);
insert into test values(8,5);
insert into test values(9,6);
求一条sql语句实现,输入一个1 把1下边的所有节点孩子及孙子输出
节点无限级在线等

解决方案 »

  1.   

    另求,反向sql,某一节点,找到祖先
      

  2.   

    mysql> select * from tb;
    +------+------+--------+
    | id   | pid  | name   |
    +------+------+--------+
    | 001  | NULL | 广东省 |
    | 002  | 001  | 广州市 |
    | 003  | 001  | 深圳市 |
    | 004  | 002  | 天河区 |
    | 005  | 003  | 罗湖区 |
    | 006  | 003  | 福田区 |
    | 007  | 003  | 宝安区 |
    | 008  | 007  | 西乡镇 |
    | 009  | 007  | 龙华镇 |
    | 010  | 007  | 松岗镇 |
    +------+------+--------+
    10 rows in set (0.00 sec)mysql> delimiter //
    mysql>
    mysql> CREATE FUNCTION `getParentLst`(NodeId CHAR(3))
        -> RETURNS varchar(1000)
        -> DETERMINISTIC
        -> -- READS SQL DATA
        -> BEGIN
        ->   DECLARE sTemp VARCHAR(1000);
        ->   DECLARE sTempChd VARCHAR(1000);
        ->
        ->   SET sTemp = '$';
        ->   set sTempChd=NodeId;
        ->    label1: LOOP
        ->      SET sTemp = concat(sTemp,',',sTempChd);
        ->      SELECT pid INTO sTempChd FROM tb where id=sTempChd;
        ->      IF FOUND_ROWS()=0 or sTempChd is null THEN
        ->          RETURN sTemp;
        ->      END IF;
        ->    END LOOP label1;
        ->   RETURN sTemp;
        -> END
        -> //
    Query OK, 0 rows affected (0.00 sec)mysql> delimiter ;
    mysql> select getParentLst('010');
    +---------------------+
    | getParentLst('010') |
    +---------------------+
    | $,010,007,003,001   |
    +---------------------+
    1 row in set (0.00 sec)mysql> select * from tb
        -> where find_in_set(id , getParentLst((select id from tb where name='松岗镇') ));
    +------+------+--------+
    | id   | pid  | name   |
    +------+------+--------+
    | 001  | NULL | 广东省 |
    | 003  | 001  | 深圳市 |
    | 007  | 003  | 宝安区 |
    | 010  | 007  | 松岗镇 |
    +------+------+--------+
    4 rows in set (0.00 sec)mysql> select * from tb
        -> where find_in_set(id , getParentLst((select id from tb where name='宝安区') ));
    +------+------+--------+
    | id   | pid  | name   |
    +------+------+--------+
    | 001  | NULL | 广东省 |
    | 003  | 001  | 深圳市 |
    | 007  | 003  | 宝安区 |
    +------+------+--------+
    3 rows in set (0.02 sec)mysql>
      

  3.   

    谢谢,能不能用sql语句直接实现呢
      

  4.   

    一条sql不行吗,数据库结构是别的程序的,我不好往数据库加东西
      

  5.   

    一条搞不定。MYSQL里面的流程判断语句,必须加到代码块里。
      

  6.   

    MySQL中进行树状所有子节点的查询 
    http://blog.csdn.net/ACMAIN_CHM/archive/2009/05/02/4142971.aspx
      

  7.   

    一条还是不行的》。
    http://blog.csdn.net/feixianxxx/archive/2010/08/15/5813272.aspx