可以在条件中使用分层查询吗?

时间:2020-02-24 07:38:24

标签: sql oracle oracle12c hierarchical-data

我将使用层次查询在Oracle Forms中构建层次树。据我所知,总部仅适用于单个表,可以在我们具有“主详细信息”业务情景的情况下使用它们。

还是可以基于视图?

例如;我想显示来自各个表的3种选项的层次结构。例如,一个客户订单可以具有各种物料。单击所有特定CO,包含其中的所有项目,某个项目可能包含子部件的“所有CO”的“第一列表”。跨多个连接的表

1 个答案:

答案 0 :(得分:1)

如果您有测试数据:

CREATE TABLE customer_orders ( id, name ) AS
SELECT 1, 'Cust. Ord. XYZ' FrOM DUAL UNION ALL
SELECT 2, 'Cust. Ord. ABC' FrOM DUAL UNION ALL
SELECT 3, 'Cust. Ord. MNO' FrOM DUAL;

CREATE TABLE customer_order_items ( id, order_id, name ) AS
SELECT 1, 3, 'MNO_NNN' FROM DUAL UNION ALL
SELECT 2, 3, 'MNO_OOO' FROM DUAL UNION ALL
SELECT 3, 3, 'MNO_MMM' FROM DUAL UNION ALL
SELECT 4, 2, 'ABC_AAA' FROM DUAL;

CREATE TABLE customer_order_item_parts ( id, item_id, name ) AS
SELECT 1, 1, 'Part_2_N' FROM DUAL UNION ALL
SELECT 2, 1, 'Part_1_N' FROM DUAL UNION ALL
SELECT 3, 2, 'Part_1_O' FROM DUAL UNION ALL
SELECT 4, 2, 'Part_3_O' FROM DUAL UNION ALL
SELECT 5, 4, 'Part_5_A' FROM DUAL UNION ALL
SELECT 6, 4, 'Part_3_A' FROM DUAL UNION ALL
SELECT 7, 4, 'Part_2_A' FROM DUAL UNION ALL
SELECT 8, 4, 'Part_4_A' FROM DUAL;

然后,您可以使用UNION ALL(和所需的JOIN)来连接数据,并在全部编译之后即可应用分层查询:

SELECT *
FROM   (
  SELECT id AS order_id,
         NULL AS item_id,
         NULL AS part_id,
         name
  FROM   customer_orders
  UNION ALL
  SELECT order_id,
         id,
         NULL,
         name
  FROM   customer_order_items
  UNION ALL
  SELECT i.order_id,
         p.item_id,
         p.id,
         p.name
  FROM   customer_order_items i
         INNER JOIN
         customer_order_item_parts p
         ON ( i.id = p.item_id )
)
START WITH item_id IS NULL
CONNECT BY NOCYCLE
      PRIOR order_id = order_id
AND   (  (   PRIOR item_id IS NULL
         AND part_id IS NULL )
      OR (   PRIOR part_id IS NULL
         AND part_id IS NOT NULL
         AND PRIOR item_id = item_id )
      )
ORDER SIBLINGS BY name

哪个输出:

ORDER_ID | ITEM_ID | PART_ID | NAME          
-------: | ------: | ------: | :-------------
       2 |    null |    null | Cust. Ord. ABC
       2 |       4 |    null | ABC_AAA       
       2 |       4 |       7 | Part_2_A      
       2 |       4 |       6 | Part_3_A      
       2 |       4 |       8 | Part_4_A      
       2 |       4 |       5 | Part_5_A      
       3 |    null |    null | Cust. Ord. MNO
       3 |       3 |    null | MNO_MMM       
       3 |       1 |    null | MNO_NNN       
       3 |       1 |       2 | Part_1_N      
       3 |       1 |       1 | Part_2_N      
       3 |       2 |    null | MNO_OOO       
       3 |       2 |       3 | Part_1_O      
       3 |       2 |       4 | Part_3_O      
       1 |    null |    null | Cust. Ord. XYZ

db <>提琴here