SQL - 加入父子表。我该如何构建此查询?

时间:2016-11-01 00:34:31

标签: jquery sql oracle join oracle11g

我有以下表格:https://i.stack.imgur.com/XIzTc.png 我需要构建一个查询来从所有表中选择数据。

我知道要在A,B,C和D之间获取数据;我应该进行左连接,但问题是当我尝试加入E和F时。

  • 是否可以在单个查询中获取所有数据?如何?
  • 我认为一种解决方案是在A和immediates子表(B,C,D)之间建立左连接,然后在BE,CE和DF中为每一行进行内连接,但这是一个很好的解决方案吗? / LI>

任何帮助都将不胜感激。

感谢。

1 个答案:

答案 0 :(得分:0)

由于没有给出数据参考,我已经为表格

采用了基于级别的输入
WITH tab_a AS
 (SELECT     'Tab_A_' || LEVEL a_id_a, 'Tab_A_VAL_' || LEVEL a_col_1,
             'Tab_A_VAL_' || (LEVEL + 10) a_col_2
        FROM DUAL
  CONNECT BY LEVEL <= 9),
 tab_b AS
 (SELECT     'Tab_A_' || LEVEL b_id_a, 'Tab_B_' || LEVEL b_id_b,
             'Tab_B_VAL_' || LEVEL b_col_1,
             'Tab_B_VAL_' || (LEVEL + 20) b_col_2
        FROM DUAL
  CONNECT BY LEVEL BETWEEN 1 AND 5),
 tab_c AS
 (SELECT     'Tab_A_' || LEVEL c_id_a, 'Tab_C_' || LEVEL c_id_c,
             'Tab_C_VAL_' || LEVEL c_col_1,
             'Tab_C_VAL_' || (LEVEL + 30) c_col_2
        FROM DUAL
  CONNECT BY LEVEL BETWEEN 1 AND 5),
 tab_d AS
 (SELECT     'Tab_A_' || LEVEL d_id_a, 'Tab_D_' || LEVEL d_id_d,
             'Tab_D_VAL_' || LEVEL d_col_1,
             'Tab_D_VAL_' || (LEVEL + 40) d_col_2
        FROM DUAL
  CONNECT BY LEVEL BETWEEN 1 AND 5),
 tab_e AS
 (SELECT     'Tab_B_' || LEVEL e_id_b, 'Tab_C_' || LEVEL e_id_c,
             'Tab_E_' || LEVEL e_id_e, 'Tab_E_VAL_' || LEVEL e_col_1,
             'Tab_E_VAL_' || (LEVEL + 50) e_col_2
        FROM DUAL
  CONNECT BY LEVEL BETWEEN 1 AND 3),
 tab_f AS
 (SELECT     'Tab_D_' || LEVEL f_id_d, 'Tab_F_' || LEVEL f_id_f,
             'Tab_F_VAL_' || LEVEL f_col_1,
             'Tab_F_VAL_' || (LEVEL + 60) f_col_2
        FROM DUAL
  CONNECT BY LEVEL BETWEEN 1 AND 4) SELECT   *
FROM tab_a a LEFT OUTER JOIN tab_b b ON (a.a_id_a = b.b_id_a)
     LEFT OUTER JOIN tab_c c ON (a.a_id_a = c.c_id_a)
     LEFT OUTER JOIN tab_d d ON (a.a_id_a = d.d_id_a)
     LEFT OUTER JOIN tab_e e
     ON (b.b_id_b = e.e_id_b AND c.c_id_c = e.e_id_c)
     LEFT OUTER JOIN tab_f f ON (d.d_id_d = f.f_id_d)ORDER BY 1

注意连接。当B&amp; C不为空时,B&amp; C与E连接。与D到F的连接相同 希望这会有所帮助。