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>
|