【问题标题】:get parent of grand children tree stored in database获取存储在数据库中的大子树的父级
【发布时间】: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 了解其他可能的选项。

标签: mysql sql tree


【解决方案1】:

试试这个 - 这将一一追踪父母,直到它到达最顶层,它会返回。

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;

将 7 替换为 6 或您想要的任何叶子。如果该叶子不存在,则不返回任何行。

【讨论】:

  • 顺便说一句,您仍然使用三个 sql 语句。但只是合而为一
  • 这些不是 3 个单独的查询。不管你深入到什么程度,这句话都会奏效。因此,如果您有 9 个 parent_id 为 6,则上述查询仍然有效。如果你想玩 SQL Fiddle - sqlfiddle.com/#!9/c083f/2
【解决方案2】:
  1. 您的问题不够清楚,无法理解您想要什么。
  2. 您还想列出一个类别表和输出

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 2017-11-16
    • 2017-12-08
    • 1970-01-01
    相关资源
    最近更新 更多