日期:2014-05-16  浏览次数:20602 次

mysql 树结构查询
id pid(父类ID)
1 0
2 1
3 1
4 2
5 2
6 4
我现在需要根据PID,查询他所有叶子节点的ID
比如查询0,得到:123456
  2,得到:456
这种层级关系不确定,可能有很多层。数据库结构已经不可能修改了
这个问题郁闷了几天了,大家帮帮忙,谢谢大侠们

------解决方案--------------------
select p2.id from table p1 ,table p2 where p1.id=p2.pid and p1.id=0
------解决方案--------------------
假设你的表名是tree
SQL code

select distinct a.id from tree as a inner join tree as b on (a.pid = b.pid) where b.pid >=0;
select distinct a.id from tree as a inner join tree as b on (a.pid = b.pid) where b.pid >=2;

------解决方案--------------------
当然这种结构你就不要追求什么效率了。如果要效率高的,只能改表结构。
------解决方案--------------------


通过程序或数据库的store procedure来实现了。 在mySQL中无法以一句SQL实现。

==== 思想重于技巧 ====