根据父表记录获取所有子记录

时间:2016-03-10 18:03:33

标签: sql

我有以下表和关系:

enter image description here

我需要获取如下记录:

enter image description here

我不知道如何才能得到它。我正在尝试以下查询,但它只显示3条记录。

SELECT A_NO, B_NO, C_NO
FROM 
(
    (SELECT * FROM S_A) A Full Outer Join
    (SELECT * FROM S_B ) B on A.ROW_ID = B.A_ID   FULL OUTER JOIN
    (SELECT * FROM S_C) C on A.ROW_ID = C.A_ID
)
WHERE A.ROW_ID = '1'

1 个答案:

答案 0 :(得分:2)

因为此处S_A-> S_B和S_A-> S_C之间没有关系,a UNION is the right way to go.

SELECT 
    S_A.A_ID,
    S_B.B_NO,
    NULL as C_NO
FROM
    S_A INNER JOIN S_B on S_A.A_ID = S_B.A_ID
UNION ALL
SELECT 
    S_A.A_ID,
    NULL as B_NO
    S_C.C_NO
FROM
    S_A INNER JOIN S_C on S_A.A_ID = S_C.A_ID

我想you could do this with一个FULL OUTER JOIN但它很笨拙,令人困惑,并且可能不会更快处理,因为你必须COALESCE()并加入子查询。

SELECT
  COALESCE(T1.A_ID, T2.A_ID),
  T1.B_NO,
  T2.C_NO
FROM
  (
    SELECT 
        S_A.A_ID,
        S_B.B_NO,
        CAST(NULL as int) as C_NO
    FROM
        S_A INNER JOIN S_B on S_A.A_ID = S_B.A_ID
  ) as t1
  FULL OUTER JOIN
  (
    SELECT 
        S_A.A_ID,
        CAST(NULL as int) as B_NO,
        S_C.C_NO
    FROM
        S_A INNER JOIN S_C on S_A.A_ID = S_C.A_ID
  ) as t2 ON t1.A_ID = T2.A_ID AND T1.B_NO = T2.B_NO