提高mySQL查询的速度

提高mySQL查询的速度,mysql,indexing,sum,accounts,Mysql,Indexing,Sum,Accounts,我有一张这样的桌子 CREATE TABLE `accounthistory` ( `id` int(11) NOT NULL AUTO_INCREMENT, `date` datetime DEFAULT NULL, `change_ammount` float DEFAULT NULL, `account_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`), ) 这是一份每日计费清单。如果我需要我使用的账户余额 从accounthi

我有一张这样的桌子

CREATE TABLE `accounthistory` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `date` datetime DEFAULT NULL,
  `change_ammount` float DEFAULT NULL,
  `account_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
)
这是一份每日计费清单。如果我需要我使用的账户余额 从accounthistory中选择sumchange\u amount,其中account\u id=; 这相当快,因为我在account_id列上添加了一个索引


但是现在我需要找出账户进入的时间减去SUMchange\u amount时的日期使查询更快的方法是:在每条记录上存储当前账户余额。要实现这一点,您必须做三件事,然后我们将了解查询的外观:

a向表中添加列:

ALTER TABLE accounthistory ADD balance float;
b填充新列

UPDATE accounthistory main SET
balance = (
    SELECT SUM(change_amount)
    FROM accounthistory
    where account_id = main.account_id
    and data <= main.date
);

谢谢我将尝试反规范化。
ALTER TABLE accounthistory ADD balance float;
UPDATE accounthistory main SET
balance = (
    SELECT SUM(change_amount)
    FROM accounthistory
    where account_id = main.account_id
    and data <= main.date
);
SELECT date
from accounthistory
where balance < 0
and balance - change_amount > 0
and account_id = ?;