它使用递归公用表表达式(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 |
+-----------+-------------+------------+------------------+
'MySQL'或'SQL Server'?它们不是同一件事。 – Siyual
@Siyual SQL Server –
在你的设计中似乎有一个缺陷。在这个设计中,一个preson可以有两个以上的父母...... –