簡體   English   中英

如何創建一列作為其他列的總和的表?

[英]How to create table having one column as sum of other columns?

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)
)

或者,您可以設置MySQL 插入觸發器 但通常,您希望在保存存儲時保持查詢計算並避免對編程對象進行維護。 另外,如果其中一項費用更新了價值,那么您需要更新觸發器。

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
$$

MySQL不支持計算列。 您可以使用視圖來實現此目的:

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

另外,不要將數字存儲為浮點數。 相反,為此目的使用固定點類型decimal

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM