在ORACLE中寻找符合specefic标准的孩子

时间:2016-06-13 13:16:42

标签: sql oracle

假设我有两张桌子: 第一个名为sales,有两列名为productquantity 第二个名为nomenclature,有两列名为compoundcomponent

每个compound可以包含多个components,每个component本身可以是compound,其中包含多个components,这使得第二个表成为层次结构。 我们以下面的表格为例:

TABLE : SALES
PRODUCT  -  QUANTITY
    P1       -  200
    P2       -  300
    F3       -  400
    P5       -  500


TABLE : NOMENCLATURE
COMPOUND - COMPONENT
P1        - A1
P1        - B2
P2        - D4
A1        - F6
B2        - Q7
D4        - F8
Q7        - F9
F9        - H10
P3        - F11

我想在SALES.PRODUCT中为每个组中的每一行找到以F开头的每个组件并返回它们和/或如果产品本身以F开头则返回自身,否则忽略该行。最终结果应如下所示:

PRODUCT - QUANTITY - COMPONENT
P1      - 200      - F6
P1      - 200      - F9
P2      - 300      - F8
F3      - 400      - F3
F3      - 400      - F11

(P5被忽略,因为它不以F开头而且没有任何以F开头的孩子)

如何以最有效的方式在PL / SQL(ORACLE)中获取此结果(NOMENCLATURE实际上有超过500k行)

1 个答案:

答案 0 :(得分:0)

你可以这样做:

WITH combined ( product, component, quantity ) AS (
  SELECT product, product, quantity FROM sales
UNION ALL
  SELECT compound, component, NULL FROM nomenclature
)
SELECT CONNECT_BY_ROOT( product ) AS product,
       CONNECT_BY_ROOT( quantity ) AS quantity,
       component
FROM   combined
WHERE  component LIKE 'F%'
START WITH quantity IS NOT NULL
CONNECT BY NOCYCLE PRIOR component = product;