Mysql 获取总消耗量

Mysql 获取总消耗量,mysql,sql,Mysql,Sql,如果我有以下表格: create table rar ( rar_id int(11) not null auto_increment primary key, rar_name varchar (20)); create table data_link( id int(11) not null auto_increment primary key, rar_id int(11) not null, foreign key(rar_id) references rar(rar_id));

如果我有以下表格:

create table rar (
rar_id int(11) not null auto_increment primary key, 
rar_name varchar (20)); 

create table data_link(
id int(11) not null auto_increment primary key,
rar_id int(11) not null,
foreign key(rar_id) references rar(rar_id));

create table consumption (
id int(11) not null,
foreign key(id) references data_link(id),
consumption int(11) not null,
total_consumption int(11) not null, 
date_time datetime not null);
我希望总消耗是所有消耗字段值的总和。有没有办法通过触发器来实现这一点?或者我是否需要每次读取所有值+最新值,将它们相加,然后更新表?有更好的方法吗

--------------------------------------------------
id | consumption | total_consumption | date_time  |
==================================================|
1  |      5      |         5         | 09/09/2013 |
2  |      5      |         10        | 10/09/2013 |
3  |      7      |         17        | 11/09/2013 |
4  |      3      |         20        | 11/09/2013 |
--------------------------------------------------
只是想知道是否有一种更干净、更快的方法可以在每次添加新条目时获得总数

或者这是个糟糕的设计?是否最好有如下内容:
从日期介于“2013-09-09”和“2013-09-11”之间的消耗中选择总和(消耗量)
以获取此类信息。。。这样做是最好的选择吗?我看到的唯一问题是,同一个命令会被多次重新运行—每次数据都不会像请求检索那样被存储……当您为了查看目的多次重新生成同一个报告时,效率可能会很低。。。。如果总数已经计算好了,你所要做的就是读取数据,而不是一次又一次地计算。。。想法


任何帮助都将不胜感激

如果你必须有触发器,它应该是这样的:

DELIMITER $$

CREATE
TRIGGER `chg_consumption` BEFORE INSERT ON `consumption` 
FOR EACH ROW BEGIN

SET NEW.total_consumption=(SELECT 
                            MAX(total_consumption)+new.consumption 
                           FROM consumption); 
END;
$$

DELIMITER ;
p、 并使
total_consumption int(11)不为null、
null或默认值为0

编辑:
SUM(total_consumpion)
改进为
MAX(total_consumpion)
as@calcinai suggestion

如果您在
total_consumpion
上有一个索引,那么将不会明显减慢查询速度,以嵌套选择
MAX(total_consumpion)
作为插入的一部分,因为最大值已经存储

例如

我不确定您是如何使用
id
列的,但是您可以很容易地将条件添加到嵌套的select中来控制这一点


如果确实需要在嵌套的select上放置WHERE,请确保在使用的字段中有一个索引,然后是
total_consumption
列。例如,如果您将其设置为
。。。如果id=x
,您需要在
(id,total_consumpion)
上建立一个索引,它才能有效地工作。

我不确定是否将total consumpion保留为自己的列。存储ID、消耗量和日期…然后在需要时使用sum语句提取总消耗量。也许这可以帮助您:您可以不用存储“累积总和”,而是动态计算。或者使用
view
like
SELECT sum(consumption)from consumption
INSERT INTO `consumption` (consumption, total_consumption) 
VALUES (8, 
    consumption + (SELECT MAX(total_consumption) FROM consumption)
);