2015-12-15 19 views
3
Create Table Billing3 
(
billingId int primary key, 
FoodCharge float DEFAULT 0, 
DoctorCharge float DEFAULT 0, 
TestCharge float DEFAULT 0, 
OperationCharge float DEFAULT 0, 
RoomCharge float DEFAULT 0, 
Total float DEFAULT (FoodCharge + DoctorCharge + TestCharge + OperationCharge + RoomCharge) 
) 
+0

不要存儲它。在你的選擇中計算它。 –

+0

我想要表格自動加起來的值 –

+1

是的,我知道。不要這樣做。 :)你需要一個觸發器來隨時更新字段。將邏輯放在select查詢中會更好。 –

回答

1

或者,您可以設置一個MySQL insert trigger。但通常情況下,您希望在存儲時節省查詢時間,並避免在編程對象上進行維護。另外,如果其中一項收費更新值,則需要更新觸發器。

USE `databasename`; 
DELIMITER 
$$ 
CREATE TRIGGER `TotalCalculation` 
BEFORE INSERT 
ON `Billing3` FOR EACH ROW 
-- Edit trigger body code below this line. Do not edit lines above this one 
BEGIN 
SET NEW.Total = NEW.FoodCharge + NEW.DoctorCharge + NEW.TestCharge + 
       NEW.OperationCharge + NEW.RoomCharge; 
END 
$$ 
0

MySQL不支持計算列。您可以爲此使用視圖:

create view v_billing3 as 
    select b.*, 
      (FoodCharge + DoctorCharge + TestCharge + OperationCharge + RoomCharge) as total 
    from billing3 b; 

另外,不要將數字存儲爲浮點數。爲此,請使用定點類型decimal

相關問題