一个字段中的值作为同一表中的查找

时间:2012-10-11 11:27:08

标签: sql ms-access lookup

我确信这很容易,但我在数据库方面很差......

我在access 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

即。一堆节点和id号 - 你可以看到/ root / x是/ root / x / y的父节点。我想创建另一个表,其中包含所有节点的列表,以及父节点的id。即:

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

以下将给出父母的身份和价值:

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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

我没有任何简单的方法来测试它。但基本思想是,在导出父节点的标题后,您可以对其进行内部联接以获取关联的ID号。