1

ここで、Dave Costa と Justin Caveから、Quantity と Price (つまり、Quantity * Price = Subtotal) の 2 つの属性から小計値を計算する方法について、(もう一度感謝します) すばらしい助けを受け取りました。回答の1つでは、小計値は他の2つの属性から導出できるため、正規化の観点からこれを行うのは良くなく、おそらくビューを使用して調べる必要があると述べられていました。私は Views を読み、概念を理解しています (関係なく他の場所で使用します) が、実際に 2 つの値を計算して結果をカスタム ビューに表示する方法がまだわかりません。誰かが私を正しい方向に向けることができれば、私はそれを感謝します.

現在のトリガー (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

Something like this, for example, will compute the subtotal by joining the order_line and product tables together just as the previous trigger was doing. Presumably, you'd want to include some additional attributes (i.e. the order number, the order line number, etc.)

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)

This has many of the same data consistency issues that the trigger-based solution had since the current price is being referenced from the product table rather than the then-current price being stored in the order_line table. If you changed the data model so that the order_line table stored the quantity and the current price, the view would get simpler because it would no longer need to join to the product table

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

If you are on 11g, you can also create a virtual column in your table definition,

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 に答える