sql - 在多级 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 数据库上运行
解决方案
您添加一个整数列,该列开始于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
关键字没有必要
join
在exists
递归查询的锚点的子查询中据推测,查询的递归部分应该 join
bom
tomlbom
而不是 self-joiningbom
。
推荐阅读
- sql - 获取分组总计的标准差的 SQL 查询
- ruby-on-rails - rails active_storage:install 给出错误
- ios - 风格顶部导航栏IOS
- css - 相对于内联元素的绝对位置
- spring-mvc - 在两个 docker 容器之间使用 FQN
- android - 迁移到 PKCS12(keystore 使用专有格式)文件名、目录名或卷标语法不正确
- vba - 带有 Excel Internet Explorer 的 vba 不使用新打开的选项卡来获取 getelemtsbytagname
- arrays - 检查一个字符串是否包含所有其他字符串
- java - Vaadin 8 网格分页
- postgresql - 生成带有“WHERE (1 <> 1)”条件的 SQL 查询