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

时间:2016-05-31 14:20:22

标签: mysql triggers insert

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

  

错误代码:1109。字段列表中的未知表employees

如果我把插入物放在触发器之前 - 一切都很完美。但是我希望这个Insert能够测试触发器。

    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);

1 个答案:

答案 0 :(得分:0)

您的触发器代码有错误 触发器代码应为:

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 ;