打印具有相同名称子项的父母的姓名

时间:2017-10-26 04:03:34

标签: sql oracle

PARENT表PK是PID,PID是FK在CHILDREN表中。如何在PARENT表中打印父母的姓名,这些父母的姓名与孩子在CHILDREN表中的名称相同?我认为应该使用递归连接来查找相同的名称,但我无法使其工作。我可以使用以下查询join PARENT和CHILDREN表:

select PARENT.NAME as ParentName
from PARENT inner join CHILDREN
on PARENT.PID=CHILDREN.PID
group by NAME;

我已经尝试过这个查询来完成递归连接但是它没有工作:

select CHILDREN.NAME
from CHILDREN e, CHILDREN m
where e.CHILDREN.PID=m.CHILDREN.PID 
order by CHILDREN.PID;

2 个答案:

答案 0 :(得分:1)

按子名分组并评估,如果至少存在两个不同的父母。

-- TEST DATA
with parent(pid, name) as
 (select 1, 'Parent1' from dual
  union all
  select 2, 'Parent2' from dual
  union all
  select 3, 'Parent3' from dual
  union all
  select 4, 'Parent4' from dual),
children(name, pid) as
 (select 'Tom', 1 from dual
  union all
  select 'Tim', 1 from dual
  union all 
  select 'Steven', 2 from dual
  union all
  select 'Tim', 2 from dual
  union all
  select 'Marta', 2 from dual
  union all
  select 'Jess', 3 from dual
  union all
  select 'Jim', 4 from dual
  union all
  select 'Jess', 4 from dual)

--> SELECT
select c.name, listagg(p.name, ',') within group(order by p.name)
  from parent p
  join children c
    on c.pid = p.pid
 group by c.name -- group by child name
having min (p.pid) <> max (p.pid) -- at least two different parents


--> RESULT
Jess    Parent3,Parent4
Tim     Parent1,Parent2

答案 1 :(得分:0)

AND Parent.Name = Children.Name 所以这不会打印父母与儿童姓名相符的名字吗?