2

私のデータベース構造

私は自分のデータベースから始めます。

ページテーブル

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_id11を取得し、parent_id 0に到達するまでそのIDのすべての親を登ることはできますか?
  • 親の総数は不明です。

多分仮想テーブル?

これが私が考えることができる仮想テーブルです。単なるアイデアであり、正しいアプローチではないかもしれません。

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

3 に答える 3

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

ところで、あなたの望む出力は間違っています;)

于 2012-11-20T16:38:16.110 に答える
0

エレガントではないかもしれませんが、'connect by' を使用せずに問題を解決するスマートな方法があります -隣接リスト モデル

于 2012-11-20T16:17:07.500 に答える
0

MySqlを使用してこれを行うスマートでエレガントな方法はありません.Oracleでは、これはどのように接続します

于 2012-11-20T16:08:44.507 に答える