2012-10-11 59 views
3

我敢肯定,這是很容易的,但我在數據庫的東西很差查找...值在一個字段作爲來自同一個表

我在訪問2003下表:

title  |  id 
/root  |  1 
/root/x  |  2 
/root/x/y |  3 
/root/x/y/z |  4 
/root/x/a |  5 
/root/x/a/b |  6 

即一堆節點和身份證號碼 - 你可以看到/ root/x是/ root/x/y的父親。我想創建另一個表,其中包含所有節點的列表以及父母的ID。即:

id | parent id 
1 | - 
2 | 1 
3 | 2 
4 | 3 
5 | 2 
6 | 5 

的follwing會給我的id和家長的價值:

select id, left(c.title, instrrev(c.title, "/")-1) as parentValue from nodeIDs 

產生

id | parentNode 
1 | 
2 | /root 
3 | /root/x 
4 | /root/x/y 
5 | /root/x 
6 | /root/x/a 

什麼是返回ID的那些公司需要額外的步驟父節點,而不是它們的值,即在最後一個表中返回'1'而不是'/ root'?

非常感謝

回答

2

像這樣的東西可能:

select c.id, 
left(c.title, instrrev(c.title, "/")-1) as parentValue 
, p.id as parentID 
from nodeIDs c 
left join 
nodeIDs p 
on left(c.title, instrrev(c.title, "/")-1) = p.title 
+0

是的 - 與'選擇ID' - >'選擇c.id'的clight更改一起使用。非常感謝 – chrisSpaceman

+0

@ user1737892是的,我很懶,用過剪切和粘貼。我錯過了那個,現在已經修好了。很高興我能幫忙,隨時接受我的回答。 –

0

這些方針的東西,我想。

select t1.id, 
     left(t1.title, instrrev(t1.title, "/")-1) as parentNode, 
     t2.id as parentID 
from nodeIDs t1 
inner join nodeIDs t2 on (left(t1.title, instrrev(t1.title, "/")-1)) = t2.title 

我沒有任何簡單的方法來測試這個。但基本思想是,在派生出父節點的標題後,可以對其進行內部連接以獲取關聯的標識號。

相關問題