首页 > 解决方案 > 在多级 BOM sql 查询中捕获级别

问题描述

我有以下查询来捕获多级 BOM。我现在知道父项的所有子项,但有没有办法在此查询中捕获级别。

with mlBOM
AS (
   select bom_item_material_number, bom_item_component
   from BOM_TABLE bom
           where not exists (
      select *
      from BOM_TABLE BOM  inner join
      BOM_TABLE  BOM1
      on BOM1.bom_item_component = BOM.bom_item_material_number
    )
   union all 
   select  BOM.bom_item_material_number, 
   BOM.bom_item_component
   from BOM_TABLE  BOM
   inner join BOM_TABLE mlBOM on mlBOM.bom_item_component = BOM.bom_item_material_number
) select * 
from mlBOM 
;

谢谢,

在 DBeaver Postgressql 数据库上运行

标签: sqlpostgresqlrecursive-query

解决方案


您添加一个整数列,该列开始于1并为每次迭代递增:

with recursive mlbom as (
    select bom_item_material_number, bom_item_component, 1 lvl
    from bom_table bom
    where not exists (
        select 1
        from bom_table bom1 
        where bom1.bom_item_component = bom.bom_item_material_number
    )
   union all 
   select bom.bom_item_material_number, bom.bom_item_component, mlbom.lvl + 1
   from bom_table bom
   inner join mlbom on mlbom.bom_item_component = bom.bom_item_material_number
) 
select * from mlbom ;

我对查询进行了一些修复:

  • cte 声明需要recursive关键字

  • 没有必要joinexists递归查询的锚点的子查询中

  • 据推测,查询的递归部分应该 join bomtomlbom而不是 self-joining bom


推荐阅读