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