【问题标题】:select child who has a parent from the same table Oracle从同一个表中选择具有父级的子级 Oracle
【发布时间】:2015-04-17 13:30:23
【问题描述】:

我在孩子的同一张桌子上有所有父亲和母亲的人表

Pen-id     firstname  lastname gender  father-id mother-id
10002       Ti         Si-dao   M       null    null
10025       Leonardo    Vogel   M       10002   10010
10010       Marissa     Wilkes  F       null    null

我需要view来显示下面的句子

Ti 是莱昂纳多·沃格尔的父亲 玛丽莎是莱昂纳多·沃格尔的母亲

我使用了 DDL,但它不起作用

CREATE VIEW parent AS
    SELECT (FIRSTNAME) ||' '|| (LASTNAME)|| (CASE WHEN GENDER ='F' THEN ' is the mother of'  ELSE 'is the father of' END) ||' '|| (FIRSTNAME) ||' '|| (LASTNAME)  AS PARENTAGE
    FROM P_PERSON ;

【问题讨论】:

  • 到底为什么需要这种将数据存储在一个表中的方式?

标签: oracle11g


【解决方案1】:

此查询将根据需要为您提供输出但也请考虑以下注释。

    select t2.firstname || ' Is Father Of '|| t1.firstname ||' '||t1.lastname 
    ||' , '||t3.firstname ||' Is Mother Of ' ||t1.firstname ||' '||t1.lastname as PARENTAGE
 from  P_PERSON  t1 , P_PERSON  t2 , P_PERSON  t3 where t1.father_id is not NULL 
    and t1.mother_id is not NULL and t1.father_id=t2.pen_id and t1.mother_id=t3.pen_id;

在这里查看Fiddle

注意:上表是不良数据库设计的示例。理想情况下你的 数据库应处于 3NF 以实现最大性能。如果可能的话 修改数据库设计。在这里使ChildParent 不同 减少头痛的对象/表格。

更新

要在单独的行上输出,您可以使用union

        select t2.firstname || ' Is Father Of '|| t1.firstname ||' '||t1.lastname 
        as PARENTAGE from P_PERSON  t1 , P_PERSON  t2  
        where t1.father_id is not NULL and t1.father_id=t2.pen_id 
        union
        select t3.firstname ||' Is Mother Of ' ||t1.firstname ||' '||t1.lastname as 
        PARENTAGE from P_PERSON  t1 ,  P_PERSON  t3 where  t1.mother_id is not NULL and 
        t1.mother_id=t3.pen_id;

在这里查看Example

【讨论】:

    猜你喜欢
    • 2013-10-22
    • 2014-01-10
    • 1970-01-01
    • 2014-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-08
    • 1970-01-01
    相关资源
    最近更新 更多