触发两个或更多,仅对两个以上做出反应

时间:2018-11-19 14:27:45

标签: mysql

CREATE TABLE IF NOT EXISTS owners (
  id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  first_name VARCHAR(30),
  last_name VARCHAR(30),
  address VARCHAR(255),
  city VARCHAR(80),
  telephone VARCHAR(20),
  INDEX(last_name)
) engine=InnoDB;

CREATE TABLE IF NOT EXISTS pets (
  id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(30),
  birth_date DATE,
  type_id INT(4) UNSIGNED NOT NULL,
  owner_id INT(4) UNSIGNED NOT NULL,
  INDEX(name),
  FOREIGN KEY (owner_id) REFERENCES owners(id),
  FOREIGN KEY (type_id) REFERENCES types(id)
) engine=InnoDB;




create trigger petadd_trigger4 before insert on pets
     for each row
         begin
         DECLARE pets_amount int;

         SELECT COUNT(*) INTO pets_amount FROM pets p WHERE p.owner_id=new.owner_id;



         if (pets_amount>=2)
         then 
         signal sqlstate '45000' SET MESSAGE_TEXT = 'Too many pets';          

         end if;

我不明白为什么只有当我添加两个以上的动物时此触发器才会做出反应。是某种错误吗?因为当我尝试添加第二只动物时它会做出反应

1 个答案:

答案 0 :(得分:0)

在插入新记录之前,触发器将为所有者计算已插入的记录。如果已经有2个,则不允许再插入一个。

我认为您正在寻找

if (pets_amount > 0)