mysql不支持递归查询。 如果预先知道最大深度的话可以使用union,比如下面认定最大深度为4:select * from a where id = ? or pid = ? union select * from a where pid in (select id from a where pid = ?) union select * from a where pid in (select id from a where pid in (select id from a where pid = ?))?转入任意一个id, 可以查询id及其所有子记录。
MySQL中进行树状所有子节点的查询
在Oracle 中我们知道有一个 Hierarchical Queries 通过CONNECT BY 我们可以方便的查了所有当前节点下的所有子节点。但很遗憾,在MySQL的目前版本中还没有对应的功能。 在MySQL中如果是有限的层次,比如我们事先如果可以确定这个树的最大深度是4, 那么所有节点为根的树的深度均不会超过4,则我们可以直接通过left join 来实现。 但很多时候我们...
如果预先知道最大深度的话可以使用union,比如下面认定最大深度为4:select * from a where id = ? or pid = ?
union
select * from a where pid in (select id from a where pid = ?)
union
select * from a where pid in (select id from a where pid in (select id from a where pid = ?))?转入任意一个id, 可以查询id及其所有子记录。