mysql 树结构查询,该怎么解决

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实现。

==== 思想重于技巧 ====
mysql 树结构查询,该怎么解决

相关文章:

你感兴趣的文章:

标签云: