分层 BOM 的最佳数据结构是什么
What's the best data structure for a hierarchical BOM
我正在尝试找出最好的模式结构来表示 Postgres 中的物料清单。假设一个部件可以有多个相同的子部件,我可以添加一个数量列,但这些部件也可能有多个子部件。
如果我想知道每个部分的总使用量,postgres 有办法在分层查询中使用数量列吗?
BOM 表示 Material 的清单。
据我了解你的问题,那么是的,你可以在使用分层 BOM 时包含数量。我理解你的问题的方式是,如果一个 BOM 条目有一个数量,例如10,那么其 children 的金额需要乘以 10(因为您有 10 倍的 "child" 项目)。
具有以下 table 和示例数据:
create table bom_entry
(
entry_id integer primary key,
product text, -- should be a foreign key to the product table
amount integer not null,
parent_id integer references bom_entry
);
insert into bom_entry
values
(1, 'Box', 1, null),
(2, 'Screw', 10, 1),
(3, 'Nut', 2, 2),
(4, 'Shim', 2, 2),
(5, 'Lock', 2, 1),
(6, 'Key', 2, 5);
所以我们的盒子需要 10 个螺丝,每个螺丝需要 2 个螺母和 2 个垫片,所以我们总共需要 20 个螺母和 20 个垫片。我们还有两把锁,每把锁有两把钥匙,所以我们一共有 4 把钥匙。
您可以使用递归 CTE 遍历树并计算每个项目的数量。
with recursive bom as (
select *, amount as amt, 1 as level
from bom_entry
where parent_id is null
union all
select c.*, p.amt * c.amount as amt, p.level + 1
from bom_entry c
join bom p on c.parent_id = p.entry_id
)
select rpad(' ', (level - 1)*2, ' ')||product as product, amount as entry_amount, amt as total_amount
from bom
order by entry_id;
rpad/level用来做缩进,使层级可视化。上面的查询returns如下:
product | entry_amount | total_amount
---------+--------------+-------------
Box | 1 | 1
Screw | 10 | 10
Nut | 2 | 20
Shim | 2 | 20
Lock | 2 | 2
Key | 2 | 4
我正在尝试找出最好的模式结构来表示 Postgres 中的物料清单。假设一个部件可以有多个相同的子部件,我可以添加一个数量列,但这些部件也可能有多个子部件。
如果我想知道每个部分的总使用量,postgres 有办法在分层查询中使用数量列吗?
BOM 表示 Material 的清单。
据我了解你的问题,那么是的,你可以在使用分层 BOM 时包含数量。我理解你的问题的方式是,如果一个 BOM 条目有一个数量,例如10,那么其 children 的金额需要乘以 10(因为您有 10 倍的 "child" 项目)。
具有以下 table 和示例数据:
create table bom_entry
(
entry_id integer primary key,
product text, -- should be a foreign key to the product table
amount integer not null,
parent_id integer references bom_entry
);
insert into bom_entry
values
(1, 'Box', 1, null),
(2, 'Screw', 10, 1),
(3, 'Nut', 2, 2),
(4, 'Shim', 2, 2),
(5, 'Lock', 2, 1),
(6, 'Key', 2, 5);
所以我们的盒子需要 10 个螺丝,每个螺丝需要 2 个螺母和 2 个垫片,所以我们总共需要 20 个螺母和 20 个垫片。我们还有两把锁,每把锁有两把钥匙,所以我们一共有 4 把钥匙。
您可以使用递归 CTE 遍历树并计算每个项目的数量。
with recursive bom as (
select *, amount as amt, 1 as level
from bom_entry
where parent_id is null
union all
select c.*, p.amt * c.amount as amt, p.level + 1
from bom_entry c
join bom p on c.parent_id = p.entry_id
)
select rpad(' ', (level - 1)*2, ' ')||product as product, amount as entry_amount, amt as total_amount
from bom
order by entry_id;
rpad/level用来做缩进,使层级可视化。上面的查询returns如下:
product | entry_amount | total_amount
---------+--------------+-------------
Box | 1 | 1
Screw | 10 | 10
Nut | 2 | 20
Shim | 2 | 20
Lock | 2 | 2
Key | 2 | 4