gpt4 book ai didi

mysql - 由于我的触发器 mysql,插入失败

转载 作者:行者123 更新时间:2023-11-29 20:57:00 25 4
gpt4 key购买 nike

我的触发代码有问题。
编写触发器后,我编写了 Insert 来测试触发器。但我的插入出现错误为

Error Code:1109. Unknown table employees in field list.

如果我将插入件放在触发器之前,一切都会完美。但我想要这个插入来测试触发器。

    drop database if exists kontrolno;
create database kontrolno;
use kontrolno;
CREATE TABLE departments(
id TINYINT UNSIGNED PRIMARY KEY,
name CHAR(12) NOT NULL,
min_salary SMALLINT UNSIGNED NOT NULL,
max_salary SMALLINT UNSIGNED NOT NULL
) ENGINE=InnoDB;
CREATE TABLE employees(
id SMALLINT UNSIGNED PRIMARY KEY,
name VARCHAR(255) NOT NULL,
salary SMALLINT UNSIGNED NOT NULL,
department_id TINYINT UNSIGNED,
constraint FOREIGN KEY (department_id)
REFERENCES departments(id)
) ENGINE=InnoDB;

insert into departments(id,name,min_salary,max_salary)
values(1,"qa", 800,2000),
(2,"jd",1200,3500);


DROP TRIGGER if exists checkSalary;
delimiter |
create trigger checkSalary before Insert on employees
for each row
begin

if(employees.salary>max_salary OR employees.salary<min_salary)
then signal sqlstate '45000' set MESSAGE_TEXT="the salary is not valide";
end if;
end;
|
delimiter ;

insert into employees(id,name,salary,department_id)
values(1,"ivan", 200,1);

最佳答案

您的触发代码有错误。
触发代码应该是:

DROP TRIGGER if exists checkSalary;
delimiter |
create trigger checkSalary before Insert on employees
for each row
begin

if(new.salary>(select max_salary from departments where id=new.department_id)
OR
new.salary<(select min_salary from departments where id=new.department_id) )
then signal sqlstate '45000' set MESSAGE_TEXT="the salary is not valid";

end if;
end;
|
delimiter ;

关于mysql - 由于我的触发器 mysql,插入失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37548301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com