工作订单的递归SQL Oracle查询

时间:2018-05-11 12:22:06

标签: sql oracle subquery recursive-query

所有

我正在尝试创建具有两个输入的递归查询:

  1. ITEM_ID
  2. LOT
  3. 我有三个工作子查询:

    1. 接收
    2. BATCH
    3. INGREDIENT
    4. 我发现可以在简单的SQL中执行此操作,例如查询:

      WITH RECURSIVE x2 (result) AS ( 
          SELECT 1 
          UNION ALL 
          SELECT result*2 FROM x2) 
      SELECT * FROM x2 LIMIT 10; 
      

      当我使用2个输入 ITEM_ID + LOT 运行第一个子查询 RECEIVING 时,它会返回一些行,然后就OK了,SQL应该停止。 如果没有,查询应开始在子查询 BATCH 中搜索 BATCH编号,此批次编号用于第三个子查询 INGREDIENT RECEIVING 返回新ITEM_ID + LOT

      Diagram for recursive subquery

      示例:

      INPUT

      1. ITEM_ID = 1765716
      2. LOT = 1EP17171590

      3. 输入输入ITEM_ID(1765716)并输入LOT(1EP17171590) 子查询 RECEIVING =>没有行返回(如果返回,结束SQL)

      4. 输入输入ITEM_ID(1765716)和LOT(1EP17171590)运行第二个子查询 BATCH =>返回BATCH_NO 351908
      5. 输入BATCH_NO(351908)运行第三个子查询 INGREDIENT =>返回新的ITEM_ID(1736957)和LOT(1FP17068674)=>转到第3点
      6. Example view

        帕特里克,

        我做了这个查询,它的工作但速度太慢,不知道如何优化它?

        select 
          BATCH_ID,
          BATCH_NO,
          PRODUCT_ITEM_ID,
          PRODUCT_ITEM
          PRODUCT_LOT,
          INGREDIENT_ITEM_ID,
          INGREDIENT_ITEM
          INGREDIENT_LOT,
          LEVEL
        FROM
          (
            SELECT 
                b.batch_id,
                b.batch_no,
                b.inventory_item_id as PRODUCT_ITEM_ID,
                b.item as PRODUCT_ITEM,
                b.lot as PRODUCT_LOT,
                i.inventory_item_id AS INGREDIENT_ITEM_ID,
                i.item as INGREDIENT_ITEM,
                i.lot as INGREDIENT_LOT
            FROM batch b
            JOIN ingredients i
            ON i.batch_id = b.batch_id
          )
        CONNECT BY NOCYCLE PRIOR 
            PRODUCT_ITEM_ID = INGREDIENT_ITEM_ID
            AND PRODUCT_LOT = INGREDIENT_LOT
        START WITH 
            PRODUCT_ITEM_ID = 1765716 
            AND PRODUCT_LOT = '1EP17171590'
        ;
        

1 个答案:

答案 0 :(得分:0)

你可以这样做而不需要递归:

我使用您在屏幕截图中提供的示例数据创建了用于此目的的表:

create table RECIEVING
(
   ITEM_ID number,
   LOT varchar2(50)
  );

insert into RECIEVING
values(1736957,'1FP17068674');

create table BATCH
(
    BATCH number,
    ITEM_ID number,
    LOT varchar2(50)
  );

insert into BATCH
values(351908,1765716,'1EP17171590');

create table INGREDIENTS
(
  BATCH number,
  ITEM_ID number,
  LOT varchar2(50)
  );

insert into INGREDIENTS
values(351908,1736957,'1FP17068674');

这是我使用的查询:

select RECIEVING.ITEM_ID,
       RECIEVING.LOT
from BATCH
join INGREDIENTS
  on BATCH.BATCH = INGREDIENTS.BATCH
join RECIEVING
  on RECIEVING.ITEM_ID = INGREDIENTS.ITEM_ID
 and RECIEVING.LOT = INGREDIENTS.LOT
where BATCH.ITEM_ID = 1765716
  and BATCH.LOT = '1EP17171590';

如果一个批次有多种成分,那么只要它在RECIEVING中存在就会返回超过1行。我不确定这是否符合您的要求。

您提供的示例的输出如下所示:

ITEM_ID     LOT
1736957     1FP17068674

SQLFiddle