MySQL怎么查询树形结构的表的数据

MySQL怎么查询树形结构的表的数据,第1张

一般比较普遍的就是四种方法:(具体见 SQL Anti-patterns这本书)

Adjacency List:每一条记录存parent_id

Path Enumerations:每一条记录存整个tree path经过的node枚举

Nested Sets:每一条记录存 nleft 和 nright

Closure Table:维护一个表,所有的tree path作为记录进行保存。

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

1:select p2.id from table p1 ,table p2 where p1.id=p2.pid and p1.id=0

2:假设表名是tree

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

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


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/6143800.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-16
下一篇 2023-03-16

发表评论

登录后才能评论

评论列表(0条)

保存