如何创建一列作为其他列的总和的表?

时间:2015-12-15 21:11:03

标签: mysql sql database

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

2 个答案:

答案 0 :(得分: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
$$

答案 1 :(得分:0)

MySQL不支持计算列。您可以使用视图来实现此目的:

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

此外,不要将数字存储为浮点数。相反,为此目的使用固定点类型decimal