如何在不省略父母的情况下返回父母及其子女



我对SQL没有超级经验,因此这可能是一个非常简单的解决方案。但是,我遇到了很多麻烦。我不能想出一个完全类似的现实情况,所以我只能逐字解释它。

我有一个具有2列的表(CGI_SUB):sub和cgi。为了易于描述,让表格别名" A"。该表中没有唯一的钥匙。每个CGI条目(" parent)都有一个相应的子条目。从关系的角度来看,CGI = parent and sub是孩子;但是,每个父母也将具有相同的子。

我要做的是输出所有CGI(包括"父级")(总共2个或更多)。本质上,只有在有孩子的情况下输出父母及其子女。

表看起来像这样

| SUB | CGI  |
______________
| TTA | TTA  |
| NSN | NSN  |
| INF | NSN  |
| VWA | VWA  |
| POR | VWA  |
| BMW | BMW  |

您可以看到,在这种情况下,NSN和VWA有"孩子",TTA和宝马没有。因此,我想输出NSN,VWA及其子女:

| SUB |
_______
| NSN |
| INF |
| VWA |
| POR |

感谢您的帮助!

craig

编辑:拼写

从x a内的x选择a.sub where(a.sub<> b.sub and a.cpi = b.cpi);

如果您只有两个级别,则分层方法可能是过分的。因此,一种方法是使用exists子句检查未匹配的父/子记录:

select a.sub
from cgi_sub a
where exists (
  select null from cgi_sub b where b.cgi = a.cgi and b.sub != b.cgi
);

将排除没有(也)该cgi行的任何行,该行没有不匹配sub

将您的样本作为CTE:

with cgi_sub (sub, cgi) as (
  select 'TTA', 'TTA' from dual
  union all select 'NSN', 'NSN' from dual
  union all select 'INF', 'NSN' from dual
  union all select 'VWA', 'VWA' from dual
  union all select 'POR', 'VWA' from dual
  union all select 'BMW', 'BMW' from dual
)
select a.sub
from cgi_sub a
where exists (
  select null from cgi_sub b where b.cgi = a.cgi and b.sub != b.cgi
);
SUB
---
INF
NSN
POR
VWA

@vani的响应使我走上了正确的轨道。这是我处理的工作

  Select Distinct(a.sub) FROM CGI_SUB a
  INNER JOIN CGI_SUB b
    ON b.cgi = a.cgi
  WHERE (a.sub <> b.sub AND a.CGI = b.CGI)

最新更新