【问题标题】:What's the best data structure for a hierarchical BOM分层 BOM 的最佳数据结构是什么
【发布时间】:2019-02-21 22:35:14
【问题描述】:

我正在尝试找出在 Postgres 中表示 BoM 的最佳模式结构。假设一个部件可以有多个相同的子部件,我可以添加一个数量列,但这些部件也可能有多个子部件。

如果我想知道每个部分的总使用量,postgres 是否可以在分层查询中使用数量列?

BOM 表示物料清单。

【问题讨论】:

  • 您好,为了避免混淆,您可能需要详细说明“BoM”在此上下文中的含义。更好的是,您可以 edit 举例说明您想要存储的数据以及您想要实现的输出。
  • 对,听起来不像是“字节序标记”。
  • 我还建议避免使用best这个词,因为没有最好的方法。在特定情况下可能有最好的方法,但一般来说(这通常是数据的存储方式)最好是模棱两可的。 (最佳 = 最小存储?最容易查询?最快检索?)

标签: postgresql hierarchical-query


【解决方案1】:

据我了解您的问题,是的,您可以在使用分层 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/level 用于缩进以可视化层次结构。上述查询返回以下内容:

product  | entry_amount | total_amount
---------+--------------+-------------
Box      |            1 |            1
  Screw  |           10 |           10
    Nut  |            2 |           20
    Shim |            2 |           20
  Lock   |            2 |            2
    Key  |            2 |            4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-21
    • 2015-11-09
    • 2014-06-26
    • 2011-10-23
    • 2018-07-17
    • 2011-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多