私は、MySQLのクロージャテーブルとしてメッセージツリーを格納しようとしています。 Bill KarwinのプレゼンテーションModels for hierarchical dataからこの方法についてほとんど学びました。問題は:私は、3つのルートノード(=祖先がないノード)を見つけたいと思っています。ツリーには最近のノードがあります。注意!たとえルートノードのサブツリーに10個の最新ノードがある場合でも、1回だけカウントされます。ツリー内の最新ノードの別個のルートノードを見つける方法(クロージャテーブルを保持)?
すべてのノードには修正時間がありますが、簡単にするために、ノードIDは最後の変更の時刻も表しています(ただしquerysで時間を表すIDは使用できません)。最初は1位、最後は17位です。私は3列(祖先、子孫、深さ)を持っているので、木はそのように提示された閉鎖テーブルで
1
2
8
15
16
17
7
3
4
5
6
9
12
10
14
11
13
:
| ancestor | descendant | depth |
+----------+------------+-------+
| 1 | 1 | 0 |
| 1 | 2 | 1 |
| 1 | 7 | 1 |
| 1 | 8 | 2 |
| 1 | 15 | 3 |
| 1 | 16 | 3 |
| 1 | 17 | 2 |
| 2 | 2 | 0 |
| 2 | 8 | 1 |
| 2 | 15 | 2 |
| 2 | 16 | 2 |
| 2 | 17 | 1 |
| 3 | 3 | 0 |
| 3 | 4 | 1 |
| 3 | 5 | 2 |
| 3 | 6 | 1 |
| 4 | 4 | 0 |
| 4 | 5 | 1 |
| 5 | 5 | 0 |
| 6 | 6 | 0 |
| 7 | 7 | 0 |
| 8 | 8 | 0 |
| 8 | 15 | 1 |
| 8 | 16 | 1 |
| 9 | 9 | 0 |
| 9 | 12 | 1 |
| 10 | 10 | 0 |
| 10 | 14 | 1 |
| 11 | 11 | 0 |
| 11 | 13 | 1 |
| 12 | 12 | 0 |
| 13 | 13 | 0 |
| 14 | 14 | 0 |
| 15 | 15 | 0 |
| 16 | 16 | 0 |
| 17 | 17 | 0 |
私はそのような最新のサブツリーを得ることができます:
SELECT c.ancestor, MAX(time) AS t
FROM closure c
JOIN nodes n ON (c.descendant = n.node AND c.ancestor <> n.node)
GROUP BY c.ancestor ORDER BY t desc;
どうすれば分かりますか?ルート最新の投稿(この場合は1、10、11)のノードはありますか? 1つのクエリでこれは可能(合理的)ですか?
編集:私は、私はデータベースにそれをシミュレートしようとした、と私は、最新の投稿を持つ最後の3つのルートノードを見つけるために、このクエリを生成sample tables to pastebin
あなたはノードtabelのためのデータ例を与えることができます:
テストデータスクリプトは、このテストの階層をロードするには? –