0

每次更新其他表时尝试重新计算一个表,但由于冗长的查询似乎无法掌握它。实际上,数量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
...

# 由限制定义的行数

但是由于语法原因似乎不起作用。坦率地说,我什至不确定它是否会达到预期的效果。

如果有更好的方法来构建上述统计页面,我会全力以赴

4

1 回答 1

0

首先也是最重要的,因为 MySQL 触发器是基于行的,因此无需重新计算所有统计信息,而是一次应用更改一条记录。

其次,您可以利用INSERT INTO ... ON DUPLICATE KEY UPDATE它来简化您的代码。要使其正常工作,您必须对表中的列进行PRIMARY KEYorUNIQUE约束。datestatistics

据说INSERTs 和DELETEs 进出您的transactions表的触发器是非常简单的单语句触发器(因此您甚至不需要更改DELIMITER和使用BEGIN ... ENDblock

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;

现在UPDATEs 有点棘手,因为日期和交易类型都可能更改。因此,我们使用OLD值来减去更新前状态下的行的值,然后应用NEW值。

DELIMITER $$
CREATE TRIGGER tg_au_transactions
AFTER UPDATE ON transactions
FOR EACH ROW
BEGIN
  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;

  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);
END$$
DELIMITER ;

这是SQLFiddle演示

于 2013-09-22T04:52:55.870 回答