尝试在每次更新其他表时重新计算表,但由于冗长的查询似乎无法掌握它。实际上,SUM
的数量更大,它基本上更新了其他用户可以查看的统计页面。
我想出了:
FOR EACH ROW BEGIN
UPDATE table 1 t1
JOIN (
SELECT date(FileDate) as SomeDate,
SUM(CASE WHEN Transaction = "Sale" then 1 else 0 end) NumSold,
SUM(CASE WHEN Transaction = "Buy" then 1 else 0 end) NumBuy,
FROM t2
GROUP BY date(FileDate)
ORDER BY year(FileDate) desc, dayofyear(FileDate) DESC
) t2 ON t1.Date = t2.Date
SET t1.NumSold = t2.NumSold, t1.NumBuy = t2.NumBuy
END
期望的结果:
SomeDate NumSold NumBuy
2013-09-19 52 51
2013-09-18 25 67
...
由限制
定义的行数但是出于语法原因似乎不起作用。坦率地说,我甚至不确定它是否会达到预期的效果。
如果有更好的方法来构建上述统计页面,我会全力以赴
答案 0 :(得分:0)
首先,最重要的是,由于MySQL触发器是基于行的,因此无需重新计算所有统计信息,而是一次更改一条记录。
其次,您可以使用INSERT INTO ... ON DUPLICATE KEY UPDATE
来简化代码。为了使其正常运行,您<{>}必须<{1}}或PRIMARY KEY
UNIQUE
列date
列{/ 1}}。
对于来自statistics
表的INSERT
和DELETE
s的触发器是非常简单的单语句触发器(因此你甚至不需要更改transactions
并使用DELIMITER
阻止)
BEGIN ... END
现在CREATE TRIGGER tg_ai_transactions
AFTER INSERT ON transactions
FOR EACH ROW
INSERT INTO statistics (date, bought, sold)
VALUES (NEW.tran_date,
CASE WHEN NEW.tran_type = 'buy' THEN 1 ELSE 0 END,
CASE WHEN NEW.tran_type = 'sale' THEN 1 ELSE 0 END)
ON DUPLICATE KEY UPDATE bought = bought + VALUES(bought),
sold = sold + VALUES(sold);
CREATE TRIGGER tg_ad_transactions
AFTER DELETE ON transactions
FOR EACH ROW
UPDATE statistics
SET bought = bought - CASE WHEN OLD.tran_type = 'buy' THEN 1 ELSE 0 END,
sold = sold - CASE WHEN OLD.tran_type = 'sale' THEN 1 ELSE 0 END
WHERE date = OLD.tran_date;
有点棘手,因为日期和事务类型都可能会被更改。因此,我们使用UPDATE
值来减去更新前状态中的行的值,然后应用OLD
值。
NEW
这是 SQLFiddle 演示