首页 > 解决方案 > 简单的家谱查询

问题描述

只有一张桌子。

表名 Family_tree。

查询尼克的所有孩子。尼克也可以当妈妈!

NAME                 ID    FATHER_ID    MOTHER_ID
--------------- ---------- ---------- ----------
Nick                  23         25        24
Jane                  10         27        26
Perl                  15         9         13
Katrin                50         6         12
Sandra                1          3          8
Demi                  2          3          8
Deimar                3          7          5
Gandalf               4          6          5
Bill                  5         10         23
Kelly                 6         22         43
Dolmar                7         11         20

标签: sqloraclehierarchical-data

解决方案


可能是这样的:

select name, father_id, mother_id from family_tree 
  where father_id in 
(select id from family_tree
  where name = 'Nick')
or mother_id in 
 (select id from family_tree
  where name = 'Nick')

或者如果您只需要尼克作为父亲,那么:

select name, father_id, mother_id from family_tree 
      where father_id in 
    (select id from family_tree
      where name = 'Nick')

此外,如果您只需要 children ,则不需要使用connect by...prior用于孙子、孙子等。


推荐阅读