2011-02-11 169 views
0

我尋找最有效的方式來遍歷一個樹層次..遍歷樹向上

我有/將有一個表,預計數百萬條記錄,樹不會改變..

在目前我存儲樹串像這樣

/20/1/1/1/1/1的

其中20是種子ID ..

如何高效地CR錐子向上?我目前有這個

select * from reg where tree in ('/20/1/1/1/1','/20/1/1/1','/20/1/1','/20/1','20') 

是否有一個SQL命令,不需要我分裂和循環呢?

我使用SQL Server和我知道CTE命令,但是當有上百萬條記錄..不能很好地執行:/

感謝

回答

1

反向的比較!

SELECT * FROM reg WHERE tree='/20/1/1/1/1' OR '/20/1/1/1/1' LIKE CONCAT(tree, "/%"); 

好運


mysql> create table temp_reg (tree varchar(255)); 
Query OK, 0 rows affected (0.01 sec) 

mysql> insert into temp_reg values ('/20/1/1/1/1'),('/30/1/1/1'),('/20/1'); 
Query OK, 3 rows affected (0.00 sec) 
Records: 3 Duplicates: 0 Warnings: 0 

mysql> select * from temp_reg where '/20/1/1/1/1' LIKE CONCAT(tree, "%"); 
+-------------+ 
| tree  | 
+-------------+ 
| /20/1/1/1/1 | 
| /20/1  | 
+-------------+ 
2 rows in set (0.00 sec) 
+0

真棒。我試圖在SQL Server中,但心不是CONCAT功能 – Alessandro 2011-02-11 16:46:28