我想用触发器计算表中的一列,但我只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:
我应该提到:如果统计表中有多个条目,我知道这个选择查询不会返回一行。我从一个空表开始,将这一行(样本)插入到统计数据中并得到 points = NULL