【问题标题】:MySQL JOIN and group by so there is one ID per rowMySQL JOIN 和 group by,所以每行有一个 ID
【发布时间】:2017-07-15 15:58:05
【问题描述】:

两个表:products,所有 ID 都是唯一的,stock,其中可以有多次相同的 ID。我需要比较 product 表中的数量与 stock 表中的总数量不匹配的数量。

产品

ID     quantity
1      4
2      6
3      2

库存:

ID     quantity
1      1
1      3
2      5
3      2

如何获得每行只有一个 ID 的结果?预期结果:

ID     quantity as products     quantity as stock

2      6                        5

【问题讨论】:

    标签: mysql join group-by


    【解决方案1】:

    您可以有一个计算总库存的子查询,并将 LEFT JOIN 它添加到您的 products 表中:

    SELECT
        products.ID, 
        products.quantity    AS `quantity as products`, 
        total_stock.quantity AS `quantity as stock`
    FROM
        products
        LEFT JOIN
        -- We compute total quantities from `stock`
        (SELECT
            stock.ID, sum(stock.quantity) AS quantity
        FROM
            stock
        GROUP BY
            stock.ID
        ) AS total_stock 
        ON total_stock.ID = products.ID
    WHERE
        -- We want to find only discrepancies.
        -- We use NOT <=> to safely check nulls.
        NOT (total_stock.quantity <=> products.quantity)
    ORDER BY
        products.ID ;
    

    我假设了这个架构(带有REFEFENCES 约束):

    CREATE TABLE products
    (
        ID INTEGER PRIMARY KEY,
        quantity INTEGER NOT NULL
    ) ;
    
    CREATE TABLE stock
    (
        ID INTEGER NOT NULL REFERENCES products(ID),
        quantity INTEGER NOT NULL
    ) ;
    

    您可以在 dbfiddle here

    找到您的示例数据(以及一些额外的数据来处理 nulls)和此解决方案

    您还可以将WHERE 子句更改为:

        -- We use coalesce to convert nulls to 0 (we assume *don't know* means *don't have*)
        coalesce(total_stock.quantity,0) <> coalesce(products.quantity, 0)
    

    取决于您的用例。

    dbfiddle here


    参考资料:

    【讨论】:

    • 谢谢!完美运行!节省了很多时间。
    • 查询工作正常。但不确定“--我们使用 NOT 来安全地检查空值”是什么。方法。我遇到了 id_product 在一个表中但不在另一个表中的情况,即 NULL,并且它没有显示它。上下文:一张表是我们的在线商店,有可供购买的可用数量,另一张表是手动检查实际库存。所以我需要从销售中删除实际上没有库存的产品。
    猜你喜欢
    • 2016-03-06
    • 1970-01-01
    • 1970-01-01
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多