-> SET sTemp = concat(sTemp,‘,‘,sTempChd);
-> SELECT group_concat(id) INTO sTempChd FROM treeNodes where FIND_IN_SET(pid,sTempChd)>0;
-> END WHILE;
-> RETURN sTemp;
-> END
-> //
Query OK, 0 rows affected (0.00 sec)
mysql>
mysql> delimiter ;
www.2cto.com
使用我们直接利用find_in_set函数配合这个getChildlst来查找
mysql> select getChildLst(1);
+-----------------+
| getChildLst(1) |
+-----------------+
| $,1,2,3,4,5,6,7 |
+-----------------+
1 row in set (0.00 sec)
mysql> select * from treeNodes
-> where FIND_IN_SET(id, getChildLst(1));
+----+----------+------+
| id | nodename | pid |
+----+----------+------+
| 1 | A | 0 |
| 2 | B | 1 |
| 3 | C | 1 |
| 4 | D | 2 |
| 5 | E | 2 |
| 6 | F | 3 |
| 7 | G | 6 |
+----+----------+------+
7 rows in set (0.01 sec)
mysql> select * from treeNodes
-> where FIND_IN_SET(id, getChildLst(3));
+----+----------+------+
| id | nodename | pid |
+----+----------+------+
| 3 | C | 1 |
| 6 | F | 3 |
| 7 | G | 6 |
+----+----------+------+
3 rows in set (0.01 sec)
--------------------------------------------
只要按我的做,百发百中弹无虚发,遇到问题万变不离其宗直接粘贴复制就是。。。
补充:
还可以做嵌套查询:
select id,pid from treeNodes where id in(
select id from treeNodes where FIND_IN_SET(id, getChildLst(3))
);
子查询的结果集是
www.2cto.com
+--------+
id
----
3
6
7
+-------+
然后经过外层查询就是
id pid
3 1
6 3
6 6
---------
转自:http://www.2cto.com/database/201209/152513.html