0

我有以下数据库结构:

RELATIONSHIP_TABLE
- id << primary key
- id_ancestor << foreign key to the same table
- id_entry << foreign key to "ENTRY_TABLE"

ENTRY_TABLE
- id
- name
...

表“ RELATIONSHIP_TABLE”中的层次结构是线性的。这意味着一个记录最多可以是另一个记录的祖先。例子:

1. record1
2. record2 <- record3 <- record4
3. record5 <- record7 <- record9 <- record12

特定层次结构中的每条记录都具有相同的“ id_entry”。现在,我想找到最后一个带有特定“ id_entry”的后代。以下示例的结果将是:

1. record1
2. record4
3. record12

有谁知道解决方案?

提前致谢 :)

QStormDS

4

1 回答 1

2
SELECT * 
FROM relationship_table rt
WHERE rt.id_entry = 42
AND NOT EXISTS (
   SELECT * FROM relationship_table nx
   WHERE nx.id_entry = 42      -- you can possibly omit this clause  
   AND nx.id_ancestor = rt.id  -- No children poining to rt ...
   )
 ;
于 2013-05-28T12:49:34.197 回答