简体   繁体   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)
)

Alternatively, you can set up a MySQL insert trigger . 或者,您可以设置MySQL 插入触发器 But usually, you want to keep calculations in queries as you save on storage and avoid maintenance on a programming object. 但通常,您希望在保存存储时保持查询计算并避免对编程对象进行维护。 Plus, if one of the charges updates values, you would then need an update 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
$$

MySQL does not support calculated columns. MySQL不支持计算列。 You can use a view for this purpose: 您可以使用视图来实现此目的:

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

Also, don't store numbers as floating points. 另外,不要将数字存储为浮点数。 Instead, use the fixed point type, decimal , for this purpose. 相反,为此目的使用固定点类型decimal

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM