获取存储在数据库中的孙子树的父级

get parent of grand children tree stored in database

我在 table 中存储了一棵树。树的结构为:

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,parent_id = 0

的顶部 cat_id

唯一的办法就是select三个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 语句的父项

  1. 你的问题不够清楚,无法理解你想要什么。
  2. 你我也想列出一个类别table和输出

试试这个 - 这将逐一追踪父级,直到到达最顶层,然后 return 那个。

select @pv from
(select @pv:=t.parent_id
from (select * from cat order by cat_id desc) t
join (select @pv := 7) tmp
where t.cat_id = @pv) a limit 1;

用 6 或任何你想要的叶子替换 7。如果该叶子不存在,则不会 return 编辑任何行。