【问题标题】:MySQL nested SELECT query with endless childsMySQL 嵌套 SELECT 查询与无穷的孩子
【发布时间】:2012-11-20 14:36:10
【问题描述】:

我的数据库结构

我从我的数据库开始。

页表

id    content
-------------
2     My content
4     Another content
7     Example content
8     Test content
11    Some content

父母表

id    page_id    parent_id
--------------------------
1     2          0
2     4          2
3     7          2
4     8          7
5     11         8

parents_table.page_id 连接到pages_table.id

问题

  • 我可以用 SQL 获取 page_id 11 并爬上该 id 的所有父母吗 直到我到达 parent_id 0?
  • 父母总数未知。

可能是虚拟桌子?

这是我能想到的,一个虚拟表。只是一个想法,可能不是正确的方法。

id    parent_id_1    parent_id_2    parent_id_3    parent_id_4    parent_id_5
-----------------------------------------------------------------------------
11    8              7              4              2              0

【问题讨论】:

  • 一些反馈如何?

标签: mysql sql database parent parent-child


【解决方案1】:

MySql 没有聪明而优雅的方法 在 Oracle 中,你已经连接了 Connect by

【讨论】:

    【解决方案2】:

    它可能不是elegant,但有一个聪明的方法可以在不使用“连接方式”的情况下解决问题 - Adjacency List Model

    【讨论】:

      【解决方案3】:

      为什么不使用存储过程?

      create table hier
      (id int, page_id int, parent_id int);
      insert into hier values
      (1    , 2,          0),
      (2   ,  4 ,         2),
      (3  ,   7  ,        2),
      (4 ,    8   ,       7),
      (5,     11   ,      8);
      
      
      drop procedure if exists getHier;
      delimiter $$
      create procedure getHier(start int)
      begin
      
      select @parent_id:=parent_id from hier where page_id = start;
      
      drop table if exists result;
      create temporary table result
      (id int primary key auto_increment,
      page_id int);
      
      insert into result (page_id) values (@parent_id);
      
      while @parent_id != 0 DO 
      insert into result (page_id)
      select @parent_id:=parent_id from hier where page_id = @parent_id;
      
      end while;
      
      select page_id from result order by id;
      end $$
      delimiter ;
      

      那就做吧

      call getHier(11)
      

      结果:

      page_id
      8
      7
      2
      0
      

      顺便说一句,你想要的输出是错误的;)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-23
        • 1970-01-01
        • 1970-01-01
        • 2015-06-16
        • 1970-01-01
        • 2017-05-03
        • 1970-01-01
        • 2014-10-13
        相关资源
        最近更新 更多