我们正在构建一个电子商务系统,需要一些帮助来确定确定每种产品有多少库存的最佳方法。
假设我们有表“products”、“products_in”和“products_out”。 “products_in”记录了我们所有增加产品数量的交易(例如,当我们从批发供应商那里购买产品时)。而“products_out”记录了我们所有减少产品数量的交易(例如,当我们的客户购买产品时)。
在我们的应用中,检索产品的可用数量比在“products_in”和“products_out”表中写入/更新记录更常见。鉴于此,使用依赖于“products_in”和“products_out”并计算可用库存的 MySQL View 是否会比每次查询时即时计算更有效?每次“products_in”或“products_out”中出现新记录时, View 上的值都会重新计算吗?或者每次我们查询时 View 都会重新计算该值(在我们的情况下这可能非常昂贵)?
最佳答案
will the use of a MySQL view that depends on "products_in" and "products_out" and computes the available stock be more efficient than computing it on the fly every time we query it? Will the value on the view be recomputed every time there's a new record in "products_in" or "products_out"? Or will the view recompute the value every time we query it (which can be quite expensive in our case)?
让我们考虑一下每种情况下的数据库步骤:
情况 1 如果每次产品进出时都计算 available_stock
并将其存储在 product
表中
- 如果产品进来,则在
product_in
表中Insert
查询;如果产品出去,则在product_out
中Insert
查询> 表 - 无论哪种情况,请更新产品的
available_stock
列中的查询。 (假设如果有 10 个产品进来或 10 个产品离开,将会触发 10 个单独的查询)- 贵吗?
情况 2 如果每次都在 View 中计算 available_stock
并且不将其存储在数据库中
- 从
product_in
和product_out
表中获取记录(仅适用于您想要available_stock
的少数产品),进行一些数学运算,然后显示预计库存 - 贵吗?
我个人会选择案例 2,因为它涉及的数据库事务总体少于案例 1,案例 1 涉及大量事务以保持库存同步。
脚注 顺便说一句,我肯定会说,如果您是铁杆“面向对象程序员”,那么您的数据库映射肯定违反了基本原理。 Products_in
、Products_out
都是记录库存/库存交易的相同实体(对象)(例如 Father
、Mother
) > 实体是 Persons
),因此您应该将它们封装到一个通用表 ProductInOutData
中。
在 ProductInOutData
中,您可以添加具有 in
值或 out
值的枚举。在一张表中同时包含 in
和 out
记录不仅可以提高可读性和可访问性,而且还有助于轻松计算进入或退出的产品,从而形成案例 2更轻量。
关于mysql - 使用 MySQL View 检索运行总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46996319/