我想计算一个带触发器的表格中的列,但我只得到NULL
作为points
的结果。
我宣布2个局部变量不执行2次查询来获取值
我认为,触发器内部的SELECT ... INTO似乎无法正常工作
select语句(没有INTO ...)有效,只返回一行
请帮助,直到现在我都想不出来......
DELIMITER //
CREATE TRIGGER calculate_points BEFORE INSERT ON stats
FOR EACH ROW
BEGIN
DECLARE pwin INT;
DECLARE pdefeat INT;
SELECT div.p_win, div.p_defeat
INTO pwin, pdefeat
FROM stats
LEFT OUTER JOIN team ON stats.team_id = team.id
LEFT OUTER JOIN div ON team.div_id = div.id;
SET new.points = new.wins * pwin - new.defeats * pdefeat;
END//
编辑#1:一些示例数据......
stats:
+----+---------+------+---------+--------+
| id | team_id | wins | defeats | points |
+----+---------+------+---------+--------+
| 1 | 1 | 3 | 1 | |
+----+---------+------+---------+--------+
team:
+----+-------+--------+
| id | name | div_id |
+----+-------+--------+
| 1 | abc | 1 |
+----+-------+--------+
div:
+----+-------+-------+----------+
| id | name | p_win | p_defeat |
+----+-------+-------+----------+
| 1 | abc | 3 | 0 |
+----+-------+-------+----------+
编辑#2:
我为更新操作测试了相同的触发器(将BEFORE INSERT
更改为BEFORE UPDATE
),这是有效的
我仍然想知道,BEFORE INSERT
会出现什么问题?!
编辑#3:
我应该提到:如果stats表中有多个条目,我知道这个select查询不返回单行。我从一个空表开始,将这一行(样本)插入到统计数据中,得到点= NULL