我正在尝试制定最佳的架构结构,以表示Postgres中的BOM。假设零件可以具有同一子部分的多个部分,我可以添加一个数量列,但是这些部分也可能有多个孩子。
如果我想知道每个部分的总用法
bom的意思是材料清单。
据我了解您的问题,是的,您可以在使用层次bom时包括数量。我理解您的问题的方式是,如果一个BOM进入的数量10,然后需要将其孩子的金额乘以10(因为您有10次"孩子"项目。
使用下表和示例数据:
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/级别用于执行凹痕以可视化层次结构。以上查询返回以下内容:
product | entry_amount | total_amount
---------+--------------+-------------
Box | 1 | 1
Screw | 10 | 10
Nut | 2 | 20
Shim | 2 | 20
Lock | 2 | 2
Key | 2 | 4