将插入触发器设置为将最大值存储在另一列中
这就是我的桌子的外观:
student_id | object_id | 总数 | 最大 |
---|---|---|---|
101 | 1 | 6 | |
102 | 2 | 5 | |
103 | 1 | 9 | |
101 | 1 | 10 101 1 10 | |
103 | 2 | 2 | |
104 | 1 | 7 |
我希望“ max ”列在总计插入。
预期输出:
student_id | object_id | 总数 | 最大 |
---|---|---|---|
101 | 1 | 10 | 10 |
102 | 2 | 5 | 7 |
103 | 1 | 9 | 10 |
101 | 1 | 8 | 10 |
103 | 2 | 2 | 7 |
104 | 1 | 7 | 10 |
我想为此创建一个触发器。
这是我的选择陈述,可以正常工作,但是如何将其放在扳机中?
WITH CTE AS (SELECT `subject_id`,MAX(`total`) AS MaxTotal
FROM results
GROUP BY `subject_id`
)
SELECT results.*,CTE.MaxTotal
FROM results
JOIN CTE ON results.`subject_id` = CTE.`subject_id`;
我这样做了,但我有很多错误
CREATE TRIGGER `max_score_before_INSERT` BEFORE INSERT ON `results`
FOR EACH ROW
SET NEW.max = (WITH CTE AS (SELECT `subject_id`,MAX(`NEW.total`) AS MaxTotal
FROM results
GROUP BY `subject_id`
)
SELECT results.*,CTE.MaxTotal
FROM results
JOIN CTE ON results.`subject_id` = CTE.`subject_id`
);
This is what my table looks like:
student_id | subject_id | total | max |
---|---|---|---|
101 | 1 | 6 | |
102 | 2 | 5 | |
103 | 1 | 9 | |
101 | 1 | 10 | |
103 | 2 | 2 | |
104 | 1 | 7 |
I want the "max" column to be automatically populated when the total is inserted.
Expected Output:
student_id | subject_id | total | max |
---|---|---|---|
101 | 1 | 10 | 10 |
102 | 2 | 5 | 7 |
103 | 1 | 9 | 10 |
101 | 1 | 8 | 10 |
103 | 2 | 2 | 7 |
104 | 1 | 7 | 10 |
I will like to create a trigger for this.
This is my SELECT statement which works fine but how do I put it in a trigger?
WITH CTE AS (SELECT `subject_id`,MAX(`total`) AS MaxTotal
FROM results
GROUP BY `subject_id`
)
SELECT results.*,CTE.MaxTotal
FROM results
JOIN CTE ON results.`subject_id` = CTE.`subject_id`;
I did this but I got a plethora of errors
CREATE TRIGGER `max_score_before_INSERT` BEFORE INSERT ON `results`
FOR EACH ROW
SET NEW.max = (WITH CTE AS (SELECT `subject_id`,MAX(`NEW.total`) AS MaxTotal
FROM results
GROUP BY `subject_id`
)
SELECT results.*,CTE.MaxTotal
FROM results
JOIN CTE ON results.`subject_id` = CTE.`subject_id`
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在触发类型之前,您不能在
内引用“ new ”。你可能想先
触发类型之后使用插入行,然后在
更新列:
请注意,此方法也会更新上一列也已经存在的行。如果不是,那么您可以在
更新
语句中使用条件:You can't reference "new" inside a
BEFORE
trigger type. You may want to firstinsert the row, then update the column with an
AFTER
trigger type:Note that this approach will update the previous columns too, as if you insert a new field that becomes the max, you may want to update the already existing rows too. If not, then you can use a condition inside the
UPDATE
statement: