Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何创建一列作为其他列总和的表?_Mysql_Sql_Database - Fatal编程技术网

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

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