触发多个或等于两个,仅对多个

kgqe7b3p  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(268)
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;

我不明白为什么这个触发器只在我加入两个以上的动物时才起作用。是某种虫子?因为当我尝试添加第二个动物时它会有React

juzqafwq

juzqafwq1#

在插入新记录之前,触发器会为所有者统计已插入的记录。如果已经有2个,则不允许插入另一个。
我想你在找

if (pets_amount > 0)

相关问题