在 postgresql 中创建多对多

Creating a many to many in postgresql

我有两个 table 需要与之建立多对多关系。我们将称为库存的 table 是通过表单填充的。其他 table 销售额通过每周将 CSV 导入数据库来填充。

Example tables image

我想遍历销售 table 并将每个销售行与库存 table 中具有相同 sku 的行相关联。这是关键。我只需要关联每个库存行的数量字段中指示的销售行数。

示例:Example image of linked tables

现在我知道我可以通过创建一个 perl 脚本来完成此操作,该脚本逐步执行销售 table 并在基于 Quantity 字段的循环中使用 ItemIDUniqueKey 字段创建链接。我想知道的是,有没有办法单独使用 SQL 命令来做到这一点?我已经阅读了很多关于多对多的内容,但我还没有找到任何人这样做。

假设表:

create table a(
    item_id integer,
    quantity integer,
    supplier_id text,
    sku text
);

create table b(
    sku text,
    sale_number integer,
    item_id integer
);

以下查询似乎符合您的要求:

update b b_updated set item_id = (
    select item_id 
    from (select *, sum(quantity) over (partition by sku order by item_id) as sum from a) a 
    where 
        a.sku=b_updated.sku and 
        (a.sum)>
            (select count(1) from b b_counted 
            where 
                b_counted.sale_number<b_updated.sale_number and
                b_counted.sku=b_updated.sku
            )
    order by a.sum asc limit 1
    );