如何在sql查询中获取子节点的父地址(oracle)

时间:2017-10-03 08:38:47

标签: sql oracle

鉴于父和子这两个表是这样的:

PARENT
id (pk)
address

CHILD
id (pk)
address
parent (fk)

Ex:
PARENT
id      address
1        West street
2        East street
3        South street

CHILD
id      address         parentid 
1        1st street      3
2        2nd street      (null)
3        (null)          2
4        4th Street      1

Expected outcome for child id in(1, 3)
childid address
1        1st Street
3        East Street

我正在寻找一个查询,其中列出了一组预定义孩子的孩子的id和地址(例如id IN(1,4,5,8,9))。如果孩子的地址为空,那么我想显示该孩子的父母的地址。 如何编写一个查询(对于Oracle数据库),它给了我想要的结果?

3 个答案:

答案 0 :(得分:0)

你需要一个案例:

select case when c.address is null then p.address else c.address end as address
from child c
     join parent p on c.parent = p.id
where c.id in (1, 4, 5, 8, 9);

答案 1 :(得分:0)

据我所知,你需要儿童身份证(在一套)中,如果他们是某人,你想显示父亲的身份......试试这个:

select coalesce(a.address,b.address) from children a 
inner join parent b on a.parent = b.id where a.id in (1,4,5,8,9)

Coalesce 会在列表中返回第一个非null表达式。因此,您将返回子ID,否则您将返回父ID(分别来自内部联接)。

内部联接交叉两个表并返回与规范匹配的行。

答案 2 :(得分:0)

您可以使用相关的子查询并合并:

SELECT id,
       COALESCE(
         address,
         ( SELECT p.address FROM parent p WHERE c.parent = p.id )
       ) AS address
FROM   children c
WHERE  id IN (1, 4, 5, 8, 9);

或者您可以使用加入:

SELECT c.id,
       COALESCE( c.address, p.address ) AS address
FROM   children c
       LEFT OUTER JOIN parent p
       ON ( c.parent = p.id )
WHERE  c.id IN (1, 4, 5, 8, 9);

(如果您没有父母的信息,请使用LEFT OUTER JOIN。)