【发布时间】:2015-07-12 09:04:42
【问题描述】:
我在表格中存储了一棵树。树的结构如下:
Category > Sub category > sub sub category
这里的父级是parent_id为0的那个。 我需要获取父 id = 0 的任何类别的 cat_id
cat_id | parent_id | name
-------------------------
1 | 0 | a
2 | 0 | b
3 | 1 | c
4 | 2 | d
5 | 3 | e
6 | 4 | f
所以对于 6 的 cat_id,父 ID = 0 的顶部 cat_id
唯一的办法就是选择三个这样的sql语句
Select parent_id where cat_id = 6 // the answer is 4
Select parent_id where cat_id = 4 // the answer is 2
Select parent_id where cat_id = 2 // the answer is 0
我需要找到一个更有效的方法来找到没有三个sql语句的父
【问题讨论】:
-
不清楚您的问题是什么,您的查询无效/您想找到更有效的查询...?我认为对于您拥有的表结构,没有更好的查询可以考虑选择更适合存储分层数据的结构。
-
@MátéJuhász 我需要找到一种更有效的方法来选择一个语句,如果可能的话
-
如果你知道你的树的最大深度,你可以使用一系列自连接,否则,这需要一个递归查询,(据我所知)MySQL 不支持。请参阅:dba.stackexchange.com/questions/46127/recursive-self-joins 了解其他可能的选项。