Mysql 如何创建一列作为其他列总和的表?
MySQL不支持计算列。您可以将视图用于此目的:Mysql 如何创建一列作为其他列总和的表?,mysql,sql,database,Mysql,Sql,Database,MySQL不支持计算列。您可以将视图用于此目的: 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 (FoodC
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)
)
另外,不要将数字存储为浮点数。为此,请使用定点类型,
decimal
。或者,您可以设置MySQL。但通常,您希望在查询中保留计算,以节省存储空间并避免对编程对象进行维护。另外,如果其中一个电荷更新了值,则需要一个更新触发器
create view v_billing3 as
select b.*,
(FoodCharge + DoctorCharge + TestCharge + OperationCharge + RoomCharge) as total
from billing3 b;
不要储存它。在你的选择中计算它。我想让表格自动将值相加,我知道。不要这样做。:)您需要一个触发器,它可以在发生更改时随时更新字段。将逻辑放在select查询中更好。
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
$$