MySQL嵌套SELECT查询与无尽的孩子

时间:2012-11-20 14:36:10

标签: mysql sql database parent parent-child

我的数据库结构

我从数据库开始。

页面表

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

3 个答案:

答案 0 :(得分:0)

使用MySql没有聪明而优雅的方法 在Oracle中,您可以通过它进行连接Connect by

答案 1 :(得分:0)

可能不是elegant,但有一种聪明的方法可以在不使用'connect by'的情况下解决问题 - Adjacency List Model

答案 2 :(得分:0)

为什么不使用存储过程?

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

BTW,你想要的输出是错误的;)

相关问题