所以我有两张桌子 - " Horses"和"结果"。 "马"列出了一系列关于每匹马的信息,包括一个名为" LTE"的信息,其总和来自"收入"来自"结果"表。 "结果"列出了最近的马展的所有结果。我使用以下代码来计算LTE -
UPDATE horses
SET horses.LTE = ( SELECT SUM(results.earnings)
FROM results WHERE horses.hname=results.hname )
这非常有效 - 它更新了LTE专栏。但是......每次我将新数据添加到"结果"我必须运行此代码。表。我将在几个月内添加数据......好吧,非常好。
我不想每次都要运行此代码。有没有办法让代码永久化,"从某种意义上说,LTE领域知道它只是在添加新信息时计算?或者MySQL不能这样工作?
Here's查看我的桌子,其中包含一些数据。
答案 0 :(得分:3)
MySQL无法正常工作。但是您可以使用triggers来实现此类功能。例如,您可以在每次插入相应表格(和/或更新)时更新您的金额,这样您将始终将您的金额“缓存”,并且可以根据需要重新计算。
如果您想要对总和更改进行更多分析,可以关注this pattern,我认为这会有所帮助
答案 1 :(得分:2)
您可以使用INSERT
,UPDATE
和DELETE
上的TRIGGER
来更新您的表格:
-- trigger for INSERT (new rows on table result).
DELIMITER |
CREATE TRIGGER ins_result AFTER INSERT ON results
FOR EACH ROW
BEGIN
UPDATE horses SET horses.LTE = (
SELECT SUM(results.earnings) FROM results WHERE horses.hname = results.hname
);
END;
|
-- trigger for UPDATE (changed rows on table result).
CREATE TRIGGER upd_result AFTER UPDATE ON results
FOR EACH ROW
BEGIN
UPDATE horses SET horses.LTE = (
SELECT SUM(results.earnings) FROM results WHERE horses.hname = results.hname
);
END;
|
-- trigger for DELETE (removed rows on table result).
CREATE TRIGGER del_result AFTER DELETE ON results
FOR EACH ROW
BEGIN
UPDATE horses SET horses.LTE = (
SELECT SUM(results.earnings) FROM results WHERE horses.hname = results.hname
);
END;
|
另一种解决方案可能是VIEW
:
CREATE VIEW v_horses AS
SELECT h.*, SUM(r.earnings) AS 'LTE'
FROM horses h INNER JOIN results r ON h.hname = r.hname
GROUP BY h.hname;
使用创建的VIEW
,您可以通过以下查询获取有关马匹的信息:
SELECT * FROM v_horses;
在您的情况下,您不使用DECIMAL
列。因此,您必须将VARCHAR
列转换为SUM
收入。因此,在您的情况下,您必须使用以下VIEW
:
CREATE VIEW v_horses AS
SELECT h.*, SUM(CAST(REPLACE(REPLACE(r.earnings, ',', ''), '$', '') AS DECIMAL)) AS 'LTE'
FROM horses h INNER JOIN results r ON h.hname = r.hname
GROUP BY h.hname;
-- for a specific year (like 2017)
CREATE VIEW v_horses AS
SELECT h.*, SUM(CAST(REPLACE(REPLACE(r.earnings, ',', ''), '$', '') AS DECIMAL)) AS 'LTE'
FROM horses h INNER JOIN results r ON h.hname = r.hname
WHERE DATE_FORMAT(STR_TO_DATE(r.`Date`, '%c/%e/%y'), '%Y') = 2017
GROUP BY h.hname;
-- grouped by year (so you can use WHERE on the VIEW):
CREATE VIEW v_horses AS
SELECT h.*, SUM(CAST(REPLACE(REPLACE(r.earnings, ',', ''), '$', '') AS DECIMAL)) AS 'LTE',
DATE_FORMAT(STR_TO_DATE(r.`Date`, '%c/%e/%y'), '%Y') AS 'year'
FROM horses h INNER JOIN results r ON h.hname = r.hname
GROUP BY h.hname, DATE_FORMAT(STR_TO_DATE(r.`Date`, '%c/%e/%y'), '%Y');
注意:如果使用此
VIEW
,您必须从表格LTE
中移除列horses
。