2011-12-08 41 views
1

我從Dave Costa和Justin Cave here(再次感謝)得到了有關如何從兩個其他屬性(數量和價格)計算小計值的絕佳幫助(所以Quantity * Price =小計)。在其中一個答案中說,從規範化的角度來看,這樣做並不好,因爲可以從其他兩個屬性派生小計值,而且我應該看看使用View。我已經閱讀了Views並獲得了這個概念(我將在別處使用它們),但我仍然不確定如何實際計算這兩個值並在自定義視圖中顯示結果。如果任何人都能指出我正確的方向,我會很感激。ORACLE - 計算兩個值並在視圖中顯示結果

當前觸發(信用給Dave和Justin):

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

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

回答

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表的存儲量和當前價格,認爲會得到更簡單,因爲它不再需要如果你是11g上加入到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 

,你還可以在您的表格定義中創建一個虛擬列,

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 
); 
相關問題