MySQL中的递归子节点路径通常指的是在树形结构中,从一个节点出发,沿着父子关系向下遍历,直到叶子节点的所有路径。这种操作在处理具有层级关系的数据时非常有用,比如组织结构、分类目录等。
MySQL支持两种主要的递归查询类型:
递归子节点路径常用于以下场景:
假设我们有一个名为employees
的表,结构如下:
| id | name | manager_id | |----|------|------------| | 1 | Alice | NULL | | 2 | Bob | 1 | | 3 | Carol | 2 | | 4 | Dave | 3 |
我们想要查询Bob的所有下属路径。
WITH RECURSIVE employee_path AS (
SELECT id, name, manager_id, CONCAT(name) AS path
FROM employees
WHERE manager_id = 2 -- Bob的ID
UNION ALL
SELECT e.id, e.name, e.manager_id, CONCAT(ep.path, ' -> ', e.name)
FROM employees e
INNER JOIN employee_path ep ON e.manager_id = ep.id
)
SELECT * FROM employee_path;
SELECT e1.name AS employee, GROUP_CONCAT(e2.name ORDER BY e2.id SEPARATOR ' -> ') AS path
FROM employees e1
LEFT JOIN employees e2 ON e1.manager_id = e2.id
WHERE e1.manager_id = 2 -- Bob的ID
GROUP BY e1.id;
innodb_lock_wait_timeout
参数来调整。领取专属 10元无门槛券
手把手带您无忧上云