帮助 mysql 触发器(插入前检查值)

发布于 2024-09-01 06:20:39 字数 825 浏览 2 评论 0原文

嗨,我对 mysql 很陌生,我正在尝试弄清楚如何使用触发器。

我正在尝试做什么: 我有 2 个表,max 和 sub_max,当我向 sub_max 插入新行时,我想检查与新行具有相同foreign_key 的值的总和是否小于 max 表中的值。我认为这听起来很令人困惑,所以这是我的表格:

CREATE TABLE max(
number  INT ,
MaxAmount integer NOT NULL)


CREATE TABLE sub_max(
sub_number  INT ,
sub_MaxAmount integer NOT NULL,
number INT,
FOREIGN KEY ( number ) REFERENCES max( number ))

这是我的触发器代码,我知道语法已关闭,但这是我通过查找教程所能做的最好的事情。

CREATE TRIGGER maxallowed
after insert on sub_max
FOR EACH ROW
BEGIN
DECLARE submax integer;
DECLARE maxmax integer;
submax = select sum(sub_MaxAmount) from sub_max where sub_number  = new.sub_number;
submax = submax + new. sub_MaxAmount;
maxmax = select MaxAmount  from max where number   = new.number ;

if max>maxmax
rollback?
END

我想知道我是否正确地远程执行此操作。提前致谢。

hi I'm quite new to mysql and I'm trying to figure out how to use triggers.

what I'm trying to do:
I have 2 tables, max and sub_max, when I insert a new row to sub_max I want to check if the SUM of the values with the same foreign_key as the new row are less than the value in the max table. I think this sounds confusing so here are my tables:

CREATE TABLE max(
number  INT ,
MaxAmount integer NOT NULL)


CREATE TABLE sub_max(
sub_number  INT ,
sub_MaxAmount integer NOT NULL,
number INT,
FOREIGN KEY ( number ) REFERENCES max( number ))

and here is my code for the trigger, I know the syntax is off but this is the best I could do from looking up tutorials.

CREATE TRIGGER maxallowed
after insert on sub_max
FOR EACH ROW
BEGIN
DECLARE submax integer;
DECLARE maxmax integer;
submax = select sum(sub_MaxAmount) from sub_max where sub_number  = new.sub_number;
submax = submax + new. sub_MaxAmount;
maxmax = select MaxAmount  from max where number   = new.number ;

if max>maxmax
rollback?
END

I wanted to know if I'm doing this remotely correctly. Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

物价感观 2024-09-08 06:20:39

警告 - 我也在学习触发器。

对于以下部分:

if max>maxmax 
rollback? 

语法会是这样的吗?:

IF max > maxmax THEN
    DELETE the id of the new record?
ELSE
    do nothing?
END IF;   

Caveat - I am also learning triggers.

For the section:

if max>maxmax 
rollback? 

Would the syntax be something like?:

IF max > maxmax THEN
    DELETE the id of the new record?
ELSE
    do nothing?
END IF;   
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文