【问题标题】:Finding difference in row count of two tables in MySQL在 MySQL 中查找两个表的行数差异
【发布时间】:2010-09-19 13:44:46
【问题描述】:

我有两张桌子,一张存储我们购买的产品和数量,另一张存储销售。因此,当前库存是买表中所有数量列的总和减去卖表中的行数。这如何在 MySQL 中表达。请记住,有许多不同的产品。

编辑: 为了让它更难,我还有另一个要求。我有购买表,出售表,但我也有产品表。我想要一份所有产品的清单,我想知道每种产品的可用数量。当前答案的问题是他们只退回我们已经出售或购买的产品。我想要所有的产品。

【问题讨论】:

标签: mysql sql count sum


【解决方案1】:

试试这个


SELECT inv_t.product_id, inventory_total-nvl(sales_total,0)
FROM 
  (SELECT product_id, sum(quantity) as inventory_total
   FROM inventory
   GROUP BY product_id) inv_t LEFT OUTER JOIN
  (SELECT product_id, count(*) AS sales_total 
   FROM sales 
   GROUP BY product_id) sale_t
  ON (inv_t.product_id = sale_t.product_id)

这是一个比其他一些发布的解决方案更好的解决方案,这些解决方案没有考虑到某些产品在销售表中可能没有任何对应行的事实。您要确保此类产品也出现在结果中。

NVL 是一个特定于 Oracle 的函数,它返回第一个参数的值,除非它为 null,在这种情况下它返回第二个参数的值。在所有商业 DBMS 中都有等效的功能——您可以在 MySQL 中使用 CASE 来达到相同的效果。

【讨论】:

  • 我认为您的意思是 inv_t.product 在第一行。
  • 感谢您的捕获,已修复。它确实显示了尚未售出的产品,这就是为什么它是外连接。我添加了一个 nvl() 调用,以表明这是应该发生的。
  • IFNULL() 在 MySQL 中做同样的事情
【解决方案2】:
SELECT product AS prd, 
SUM(quantity) - 
  IFNULL((SELECT COUNT(*)
   FROM sells
   WHERE product = prd 
   GROUP BY product), 0)
AS stock 
FROM bought
GROUP BY product;

当销售数量为 0 时,此方法也有效。

【讨论】:

    【解决方案3】:

    我建议将“inventory”和“sales”表制作成视图,这样它们就可以重用并且最终的查询变得非常简单。显然,字段和表名需要更改以匹配您的架构。

    --First view: list products and the purchased qty
    create or replace view product_purchases as
    select
      product_id
     ,sum(purchased_qty) as purchased_qty
    from
      purchases
    group by
      product_id;
    
    --Second view: list of products and the amount sold    
    create or replace view product_sales as
    select
      product_id
     ,count(*) as sales_qty
    from
      sales
    group by
      product_id;
    
    --after creating those two views, run this query:
    select
      pp.product_id
     ,pp.purchased_qty - ps.sales_qty as on_hand_qty
    from
      product_purchases pp
     ,product_sales ps
    where ps.product_id = pp.product_id;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-25
      • 1970-01-01
      • 2015-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多