2017-02-16 65 views
1

我需要做一个简单的数据库,这些表:简单的家庭数据库

表1(people表)

Person_ID INT, 
Person_name TEXT, 
Person_age INT, 
Person_birthdate DATE 

表2(父&子表)

Parent_ID INT, 
Child_ID INT 

在第一张表中,我所有的家庭成员都输入了基本信息在第二个表格中,每个父母都与他们的孩子一起进入。

例如:我妈妈有ID#77,我爸爸有ID#42,我有ID 53。在第二个表中的行将是:

Parent ID | Child ID 
77  | 53 
42  | 53 

我的问题是我如何从一个人ID打印上一代的所有孩子?

+0

'MySQL'或'SQL Server'?它们不是同一件事。 – Siyual

+0

@Siyual SQL Server –

+0

在你的设计中似乎有一个缺陷。在这个设计中,一个preson可以有两个以上的父母...... –

回答

0

它使用递归公用表表达式(cte)获取所有后代,连接到Person表以获取详细信息,并筛选出带有自己子女的人not exists()

测试设置:http://rextester.com/QTTIS9257

create table Person (
    Person_Id int 
    , Person_Name varchar(32) 
    , Person_Age int 
    , Person_BirthDate date 
); 
insert into Person (Person_Id, Person_Name) values 
(53,'Bader'); 

create table ParentChild (
    Child_Id int not null 
    , Parent_Id int null 
); 
insert into ParentChild values 
(53,42),(53,77),(42,21),(77,9),(9,null),(21,null); 

declare @PersonId int; 
set @PersonId = 9; -- Parent to 77 

/* recursive cte to get all descendantsof @PersonId*/ 
with cte as (
select Parent_Id, Child_Id 
    from ParentChild 
    where Parent_Id = @PersonId 
union all 
select c.Parent_Id, c.Child_Id 
from ParentChild c 
    inner join cte p 
    on c.Parent_Id = p.Child_Id 
) 

/* join Person to cte to get Person's details */ 
select p.* 
    from Person as p 
     inner join cte 
     on p.Person_Id = cte.Child_Id 
/* don't return children who are parents */ 
where not exists (
    select 1 
    from cte i 
    where i.Parent_Id = p.Person_Id 
); 

结果:

+-----------+-------------+------------+------------------+ 
| Person_Id | Person_Name | Person_Age | Person_BirthDate | 
+-----------+-------------+------------+------------------+ 
|  53 | Bader  | NULL  | NULL    | 
+-----------+-------------+------------+------------------+ 
+0

谢谢,你救了我<3 –

+0

@BaderAli乐意帮忙!如果这个答案适合你,请接受它。 – SqlZim