我试图了解 MySQL 递归查询的工作原理并以我想要的方式获取数据。
现在我有以下 SQL
SELECT `Library`.*, l2.*, l3.*
FROM `Library`
LEFT JOIN `Library` as `l2` on `l2`.`subsectionOf`=`Library`.`iD`
LEFT JOIN `Library` as `l3` on `l3`.`subsectionOf`=`l2`.`iD`
WHERE `Library`.`iD` = 0x02
ORDER BY `Library`.`subsectionOrder`, `l2`.`subsectionOrder`, `l3`.`subsectionOrder`
这为我提供了 3 级深的数据层次结构,布局如下:
Layer 1 fields, Layer 2 fields, Layer 3 fields
- 如何使查询适用于 n 个深度?
如何使结果堆叠在一起,而不是在右侧添加字段?
Layer 1 Row Layer 2 Row Layer 2 Row Layer 3 Row Layer 3 Row Layer 2 Row Layer 3 Row Layer 2 Row
最佳答案
MySQL 不支持递归 SQL 查询。大多数人以不同的方式存储分层数据,因此他们可以在单个查询中获取整个树。
查看我对 What is the most efficient/elegant way to parse a flat table into a tree? 的回答
我有一个演示Models for Hierarchical Data with SQL and PHP ,我在我的书中写了关于树结构数据的文章 SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming .
@Quassnoi 在他对 Hierarchical queries in MySQL 的回答中给出了另一个棘手的解决方案。就在这里。
关于mysql - 尝试理解 MySQL 自连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8171668/