|
| WIKI | SNS | PC | BOOK |
|
階層構造を持つデータを、リレーショナルデータベースで扱うには、どうしたら良いでしょうか?
階層構造を持つデータは、いろいろありますねー。 データベースに階層的なデータを格納する †Storing Hierarchical Data in a Database
Storing Hierarchical Data in a Database
Whether you want to build your own forum, publish the messages from a mailing list on your Website, or write your own cms: there will be a moment that you'll want to store hierarchical data in a database. あなたが自分用の会議場を作りたいとか、自分のサイトのメーリングリストにメッセージを発表したいとか、自分のCMSに書き込みしたいとか、いずれにしても、データベースに階層的なデータを格納したい時があるでしょう。 Storing trees is a common problem, with multiple solutions. ツリー(注:樹形のデータ構造)を格納することは、複数の解決方法がある一般的な問題です。 In this article, we'll explore these two methods of saving hierarchical data. この記事では、階層的なデータを保存する二つの方法を探究します。例として、架空のオンライン食品店を引用して、ツリーを使ってみます。この食品店は、カテゴリー、色、タイプによって、食品を整理しています。このツリーは、次のようになっています。 This article contains a number of code examples that show how to save and retrieve data. この記事には、どのようにデータを保存して検索するかを示す、多くのコードの例を含んでいます。私が自分でその言語を使っていて、他の多くの人々がその言語を使っているか知っているという理由で、私はPHPで例を書くことを選びました。あなたはたぶん簡単にそれらを、あなた自身が選択した言語に翻訳することができます。 隣接リストモデル †The Adjacency List Model The first, and most elegant, approach we'll try is called the 'adjacency list model' or the 'recursion method'. 私たちが試みる最初の上品なアプローチは、「隣接モデルリスト」または「再帰法」というものです。それは、あなたが必要とする、ツリーによる繰返しの簡潔な機能なので、上品なアプローチです。私たちの食品店では、隣接リストのためのテーブルが次のようになります。 As you can see, in the adjacency list method, you save the 'parent' of each node. お分かりのように、隣接リスト法で、あなたはそれぞれのノードの「親」を保存しておきます。「梨(Pear)」は「緑(Green)」の子供であり、「緑」は「果物(Fruit)」の子供である、等が分かります。根本のノード「食品(Food)」は、親の値を持っていません。単純に、「タイトル」値を各ノードの識別のために使います。もちろん、実際のデータベースの中では、各ノードの数値IDを使います。 ツリーを用意 †Give Me the Tree Now that we've inserted our tree in the database, it's time to write a display function. ツリーをデータベースに追加したので、表示する関数を書くべき時です。この関数は、根のノード―親のいないノード―からスタートしなければならないでしょう。そして次に、そのノードの全ての子を表示するべきです。各々の子に対して、関数は、その子の全ての子ノードを検索して、表示するべきです。それらの子に対して、関数は全ての子をさらに表示するべきです。 As you might have noticed, there's a regular pattern in the description of this function. お気付きのように、この関数の記述には規則的なパターンがあります。私たちは簡潔に、ある親ノードの子を検索する一つの関数を書けます。関数は、すべての子を表示するために、各子ノードに対して、子ノードのもう一つ別のインスタンスを作るべきです。これは「再帰法」という名の再帰的なメカニズムです。 <?php
// $parent is the parent of the children we want to see
// $parent は見たい子の親です。
// $level is increased when we go deeper into the tree,
// used to display a nice indented tree
// $level は、適切に字下げされたツリーを表示するために使われ、
//ツリーに深くに入るほど増加されます。
function display_children($parent, $level) {
// retrieve all children of $parent
// $parent の全ての子を検索
$result = mysql_query('SELECT title FROM tree '.
'WHERE parent="'.$parent.'";');
// display each child
// 各々の子を表示
while ($row = mysql_fetch_array($result)) {
// indent and display the title of this child
// 子のタイトルを字下げして表示
echo str_repeat(' ',$level).$row['title']."\n";
// call this function again to display this
// child's children
// 子の子を表示するために関数を再呼出し
display_children($row['title'], $level+1);
}
}
?>
To display our whole tree, we'll run the function with an empty string as $parent and $level = 0: display_children('',0); For our food store tree, the function returns: 全体のツリーを表示するために、$parentを空の文字列に、$levelを0にして、関数を実行します。つまり、display_children('',0)にします。食品店のツリーに対して、関数は以下のように返します。 Food Fruit Red Cherry Yellow Banana Meat Beef Pork 食物 果物 赤 チェリー 黄色 バナナ 肉 牛肉 豚肉 Note that if you just want to see a subtree, you can tell the function to start with another node. For example, to display the 'Fruit' subtree, you would run display_children('Fruit',0); あなたがサブツリーを見たいなら、関数に対して別のノードから始めるように指示できることに注意してください。例えば、「フルーツ」のサブツリーを表示するために、あなたは、display_children('Fruit',0);と実行するでしょう。 ノードへの経路 †The Path to a Node With almost the same function, it's possible to look up the path to a node if you only know the name or id of that node. ほとんど同じ関数で、あなたがノードの名前かidを知っていれば、そのノードへの経路を探すことが可能です。例えば、「チェリー」への経路は、「フード」>「フルーツ」>「赤」です。この経路を得るために、私たちの関数は、「チェリー」という最も深いレベルから開始しなければならないでしょう。それは、次に、このノードの親を訪ねて、経路にこれを加えます。私たちの例では、これは「赤」でしょう。もし「赤」が「チェリー」の親であることを知れば、「赤」への経路を使って、「チェリー」への経路を計算できます。再帰的に親を探すことによって、ツリー中のあらゆるノードの経路を得ることが、今まで使ってきた関数でもたらされます。 <?php
// $node is the name of the node we want the path of
function get_path($node) {
// look up the parent of this node
$result = mysql_query('SELECT parent FROM tree '.
'WHERE title="'.$node.'";');
$row = mysql_fetch_array($result);
// save the path in this array
$path = array();
// only continue if this $node isn't the root node
// (that's the node with no parent)
if ($row['parent']!='') {
// the last part of the path to $node, is the name
// of the parent of $node
$path[] = $row['parent'];
// we should add the path to the parent of this node
// to the path
$path = array_merge(get_path($row['parent']), $path);
}
// return the path
return $path;
}
?>
This function now returns the path to a given node. この関数は、今や、与えられたノードへの経路を返します。それは、配列として経路を返すので、経路を表示するために、print_r(get_path('Cherry'));を使うことができます。もしあなたがこれを「チェリー」に対してなしたら、あなたは次のような結果を見るでしょう。 Array ( [0] => Food [1] => Fruit [2] => Red ) 不都合 †Disadvantages As we've just seen, this is a great method. 私たちが見てきたように、これは優れた方法です。理解することが簡単で、必要なコードも単純です。それなら、隣接リストモデルのマイナス面は何でしょうか?ほとんどのプログラミング言語で、遅くて非能率的なことです。これは主に、再帰によって引き起こされます。ツリー中の各ノードごとに、1回のデータベースクエリーが必要になります。 As each query takes some time, this makes the function very slow when dealing with large trees. 各クエリーにある程度の時間がかかることが、大きなツリーを処理するとき、この関数を非常に遅くさせます。 The second reason this method isn't that fast, is the programming language you'll probably use. この方法が速くない2番目の理由は、あなたの使うプログラミング言語です。Lispのような言語と違って、たいていの言語は再帰関数のために設計されていません。それぞれのノードに対して、関数は、自分のもう一つのインスタンスを開始します。したがって、4階層のツリーに対しては、同時に4個の関数のインスタンスを実行するでしょう。それぞれの関数がメモリの一部分を確保して、さらに初期化するためにある程度の時間を要するので、再帰は大きなツリーに用いられる場合にはとても遅いです。 修正された前順走査のツリー移動 (木の幹からの探索) †Modified Preorder Tree Traversal Now, let's have a look at another method for storing trees. 今、木を蓄える別の方法をちょっと見ましょう。 We'll start by laying out our tree in a horizontal way. 私たちは、地平線の方法で私たちの木をレイアウトすることから始めるでしょう。根節(「食べ物」)で始まって、そしてそれの左側へ1を書いて下さい。「果物」まで木の後ろについていって、そしてそれの隣に2を書いて下さい。このように、左側の数字と右のそれぞれの節の横腹を書いている間に、あなたは、木の端に沿って(走査)歩きます。最後の数字は、「食べ物」節の右側で書かれます。このイメージで、あなたは、数えられている順序を示すために、全く限られている木と少しの矢を見ることができます。 We'll call these numbers left and right (e.g. the left value of 'Food' is 1, the right value is 18). 私たちは、これらの数字を左であって、正しい(例えば「食べ物」の左側価値、1、正しい価値が18だということである)と思うでしょう。あなたが見ることができるので、これらの数字は、それぞれの節における関係を示します。「赤」が3番および6を持っているので、それは、1-18の「食べ物」節の子孫です。同じように、私たちは、左の価値が2と右が11未満を評価するよりもすばらしい状態で、すべてがうなずくことが2-11「果物」の子孫だと言うことができます。木構造は、左側と正しい価値で今、しまっておかれます。図表のあたりに歩いて節を数えることのこの方法が呼ばれますその’修正します木移動のアルゴリズムを前注文して下さい。 Before we continue, let's see how these values look in our table: 私たちが続く前に、どのようにこれらの価値が私たちのテーブルをのぞいて見るかを確認しましょう: Note that the words 'left' and 'right' have a special meaning in SQL. その単語が「去って」、そして「正しく」SQLで意味しているスペシャルを持っていることに注意して下さい。 木を回収して下さい †Retrieve the Tree If you want to display the tree using a table with left and right values, you'll first have to identify the nodes that you want to retrieve. もし左のまた正しい価値でテーブルを利用した木を展示したければ、あなたは、初めにそれ持ってきたい節を明らかにする必要があるでしょう。 SELECT * FROM tree WHERE lft BETWEEN 2 AND 11; That returns: それは戻ります: Well, there it is: a whole tree in one query. まあ、そこにそれがあります:1つの質問のすべての木。 SELECT * FROM tree WHERE lft BETWEEN 2 AND 11 ORDER BY lft ASC; The only problem left is the indentation. 唯一の問題左方は、ギザギザです。 To show the tree structure, children should be indented slightly more than their parent. 木構造を見せるために、子供は、わずかに彼らの親よりも多くへこむべきです。 <?php
function display_tree($root) {
// retrieve the left and right value of the $root node
$result = mysql_query('SELECT lft, rgt FROM tree '.
'WHERE title="'.$root.'";');
$row = mysql_fetch_array($result);
// start with an empty $right stack
$right = array();
// now, retrieve all descendants of the $root node
$result = mysql_query('SELECT title, lft, rgt FROM tree '.
'WHERE lft BETWEEN '.$row['lft'].' AND '.
$row['rgt'].' ORDER BY lft ASC;');
// display each row
while ($row = mysql_fetch_array($result)) {
// only check stack if there is one
if (count($right)>0) {
// check if we should remove a node from the stack
while ($right[count($right)-1]<$row['rgt']) {
array_pop($right);
}
}
// display indented node title
echo str_repeat(' ',count($right)).$row['title']."\n";
// add this node to the stack
$right[] = $row['rgt'];
}
}
?>
If you run this code, you'll get exactly the same tree as with the recursive function discussed above. もしこのコードを走らせれば、あなたは、上の機能が議論した帰納的であることとちょうど同じ木を得るでしょう。 節への道 †The Path to a Node With this new algorithm, we'll also have to find a new way to get the path to a specific node. この新しいアルゴリズムで、私たちは、特定の節への道を得る新しい方法を見つける必要がまたあるでしょう。 With our new table structure, that really isn't much work. 私たちの新しいテーブル構造で、それは本当に多くの仕事ではありません。 SELECT title FROM tree WHERE lft < 4 AND rgt > 5 ORDER BY lft ASC; Note that, just like in our previous query, we have to use an ORDER BY clause to sort the nodes. 私たちの前の質問で、私たちが節によって順序を使う必要があるようにそれを書きとめて節を分類して下さい。 +-------+ | title | +-------+ | Food | | Fruit | | Red | +-------+ We now only have to join the rows to get the path to 'Cherry'. 私たちは、「サクランボ」への道を得るために、今、列に加わるだけでよいです。 何人の子孫 †How Many Descendants If you give me the left and right values of a node, I can tell you how many descendants it has by using a little math. もしあなたが私に節の左側と正しい価値を与えれば、私は、あなたに、いくつの子孫をそれが少しの数学を使うことによって持っているかを話すことができます。 As each descendant increments the right value of the node with 2, the number of descendants can be calculated with: それぞれ降下性の増加として、2をもつ節の正しい価値、以下で子孫の数が計算されることができます: descendants = (right - left - 1) / 2 With this simple formula, I can tell you that the 2-11 'Fruit' node has 4 descendant nodes and that the 8-9 'Banana' node is just a child, not a parent. この単純な公式で、私は、あなたに,2-11の「果物」節が4つの子孫節を持っている、および8-9つの「バナナ」節がちょうど親ではなく子供だと話すことができます。 木移動を自動化して †Automating the Tree Traversal Now that you've seen some of the handy things you can do with this table, it's time to learn how we can automate the creation of this table. あなたがこのテーブルであなたがすることができるその便利な物の一部を見たので、どのように私たちがこのテーブルの創造を自動化することができるかを知る時間です。 Let's write a script that converts an adjacency list to a modified preorder tree traversal table. それが隣接リストを変える台本を書きましょうひとつの修正します木移動テーブルを前注文して下さい。 <?php
function rebuild_tree($parent, $left) {
// the right value of this node is the left value + 1
$right = $left+1;
// get all children of this node
$result = mysql_query('SELECT title FROM tree '.
'WHERE parent="'.$parent.'";');
while ($row = mysql_fetch_array($result)) {
// recursive execution of this function for each
// child of this node
// $right is the current right value, which is
// incremented by the rebuild_tree function
$right = rebuild_tree($row['title'], $right);
}
// we've got the left value, and now that we've processed
// the children of this node we also know the right value
mysql_query('UPDATE tree SET lft='.$left.', rgt='.
$right.' WHERE title="'.$parent.'";');
// return the right value of this node + 1
return $right+1;
}
?>
This is a recursive function. これは帰納的な機能です。 If there are no children, it sets its left and right values. もしそこにが決して子供でなければ、それは、その左のまた正しい価値をセットします。 The recursion makes this a fairly complex function to understand. 回帰は、理解するために、これをとても複雑な機能にします。 節を加えること †Adding a Node How do we add a node to the tree?
どのように私たちは、木に節を加えますか?
The first option is simple. 最初のオプションは単純です。 The second way to add, and delete nodes is to update the left and right values of all nodes to the right of the new node. 節を加えて削除する第2の方法は、新しい節の右側にすべての節の左側と正しい価値を更新することです。 We'll use the query: 私たちは質問を使うでしょう: UPDATE tree SET rgt=rgt+2 WHERE rgt>5; UPDATE tree SET lft=lft+2 WHERE lft>5; Now we can add a new node 'Strawberry' to fill the new space. This node has left 6 and right 7. 私たちが新しい節「イチゴ」を加えることができる今は、新しい空間を満たします。この節は、6と右7を去りました。 INSERT INTO tree SET lft=6, rgt=7, title='Strawberry'; If we run our display_tree() function, we'll see that our new 'Strawberry' node has been successfully inserted into the tree: 私たちが私たちの表示_木を走らせるか()機能、私たちは、私たちの新しい「イチゴ」節が木へうまく挿入されたことを確認するでしょう: Food
Fruit
Red
Cherry
Strawberry
Yellow
Banana
Meat
Beef
Pork
不利 †Disadvantages At first, the modified preorder tree traversal algorithm seems difficult to understand. はじめは、修正されたことは、移動アルゴリズムが理解するために難しいようである木を前注文します。 結論 †Conclusion You're now familiar with both ways to store trees in a database. あなたは、今、木をデータベースに保存する両方の方法をよく知っています。 One last note: as I've already said I don't recommend that you use the title of a node to refer to that node. 1枚の最新(最後)のメモ:私がすでに言ったように、私は、その節を参照するために、あなたが節のタイトルを使うことを勧めません。 更なる読書 †Further Reading More on Trees in SQL by database wizard Joe Celko: Two other ways to handle hierarchical data: Xindice, the 'native XML database': An explanation of recursion: |