首页 > 解决方案 > 在 MySQL 中获取所有具有路径的父母

问题描述

我有一张像这样的桌子;

id | rank | path
---+------+-------
 1 | NULL | NULL
 2 |  1   | /1/2/
 3 |  2   | /1/2/3/
 4 |  2   | /1/2/3/
 5 |  3   | /1/2/3/5/
 6 |  1   | /1/6/

给定从 id 5 或 id 5 开始的路径,希望所有父母都喜欢;

 1 | NULL | NULL
 2 |  1   | /1/2/
 3 |  2   | /1/2/3/
 4 |  2   | /1/2/3/
 5 |  3   | /1/2/3/5/

或者

 1 | NULL | NULL
 2 |  1   | /1/2/
 3 |  2   | /1/2/3/
 4 |  2   | /1/2/3/

试过这里的建议SQL: How to select all parent nodes in Materialized path? 但没有成功。

我尝试的查询是:

SELECT * FROM table
WHERE '/1/2/3/5/' LIKE id||%
ORDER BY path

此外,我查看了来自 - https://communities.bmc.com/docs/DOC-9902 - https://www.sqlteam.com/articles/more-trees-hierarchies-in-sql的查询

其中。找不到适合这个的东西。

请协助。

标签: mysqlmysql-5.7

解决方案


推荐阅读