1

我从 Dave Costa 和 Justin Cave那里得到了极好的帮助(再次感谢),如何从其他两个属性计算小计值,数量和价格(所以数量 * 价格 = 小计)。在其中一个答案中指出,从规范化的角度来看,这样做并不好,因为小计值可以从其他两个属性中得出,我可能应该考虑使用视图。我已经阅读了 Views 并得到了这个概念(无论如何我都会在其他地方使用它们),但我仍然不确定如何实际计算这两个值并在自定义视图中显示结果。如果有人能指出我正确的方向,我将不胜感激。

当前触发器(归功于 Dave 和 Justin):

CREATE VIEW show_subtotal 
AS SELECT price 
FROM products
WHERE product_no =:new.product_no;

:new.subtotal := currentPrice * :new.quantity;

4

1 回答 1

3

例如,这样的事情将通过将order_lineproduct表连接在一起来计算小计,就像之前的触发器所做的那样。大概,您想要包含一些额外的属性(即订单号、订单行号等)

CREATE OR REPLACE VIEW order_line_with_subtotal( product_no,
                                                 quantity, 
                                                 price,
                                                 subtotal )
AS
SELECT ol.product_no,
       ol.quantity,
       p.price,
       (ol.quantity * p.price) subtotal
  FROM order_line ol
       JOIN product p ON (ol.product_no = p.product_no)

这与基于触发器的解决方案存在许多相同的数据一致性问题,因为当前价格是从product表中引用的,而不是当前价格存储在order_line表中。如果您更改数据模型以便order_line表格存储数量和当前价格,则视图会变得更简单,因为它不再需要连接到product表格

CREATE OR REPLACE VIEW order_line_with_subtotal( product_no,
                                                 quantity, 
                                                 price,
                                                 subtotal )
AS
SELECT ol.product_no,
       ol.quantity,
       ol.price,
       (ol.quantity * ol.price) subtotal
  FROM order_line ol

如果您使用的是 11g,您还可以在表定义中创建一个虚拟列,

CREATE TABLE order_line (
  order_line_no NUMBER PRIMARY KEY,
  order_no      NUMBER REFERENCES order( order_no ),
  price         NUMBER,
  quantity      NUMBER,
  subtotal      NUMBER GENERATED ALWAYS AS (price*quantity) VIRTUAL 
);
于 2011-12-08T19:31:13.990 回答