我有一个包含以下列的表格
id | parent_customer_id
-----------------------------
1 | 0
2 | 0
3 | 1
4 | 2
5 | 4
6 | 4
我想要一个可以返回某个客户的所有子 ID 的脚本。例如
get_child_ids (1) = 1,3
get_child_ids(2) = 2,4,5,6
get_child_ids(3) = 3
get_child_ids(4) = 4,5,6
get_child_ids(5) = 5
get_child_ids(6) = 6
某些 ID 的深度可达 10 级。我在 https://explainextended.com/2009/07/20/hierarchical-data-in-mysql-parents-and-children-in-one-query/ 找到了一个获取父 ID 的好方法。但我很难带上 child
最佳答案
最好的解决方案是“使用 CTE 语法编写递归 SQL 查询”,但直到 MySQL 8.0.1 才支持此操作。
递归 CTE 语法是标准 SQL,现在 MySQL 也支持它,所有流行品牌的 SQL 兼容产品都支持它。
我在 2017 年 4 月的 Percona Live Conference 上做了关于 MySQL 中即将推出的递归查询功能的演示:Recursive Query Throwdown in MySQL 8 .
WITH RECURSIVE MyCTE AS (
SELECT id, parent_customer_id FROM MyTable WHERE id = ?
UNION
SELECT id, parent_customer_id FROM MyTable JOIN MyCTE
ON MyTable.parent_customer_id = MyCTE.id
)
SELECT * FROM MyCTE;
如果您无法使用MySQL 8.0.1或更高版本,您可以使用ExplainExtended中的巧妙解决方案,或者您可以以其他方式存储分层数据以支持非递归查询。
我在演示中展示了许多解决方案 Models for hierarchical data ,或者在我对 What is the most efficient/elegant way to parse a flat table into a tree? 的回答中.
我还在我的书 SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming 中写了一个关于此的章节。 .
关于mysql - 如何获取MYSQL分层数据中的所有子记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44604589/