mysql - 插入后在触发器中循环

标签 mysql triggers

我不小心删除了触发器(需要重置数据库中的某些内容)。但是我不知道如何再次触发我的触发器..

我有 2 个表。

1:

火车信息:

train_information table

2:

车轴:
axle table

现在,当火车被添加并插入到数据库表中时:train_information。我想要一个触发器来更新轴表。

触发器工作后,我希望轴表看起来像:

How i want the table to look after insert

但是。如果 train_information 有 4 个轴。我只想把 3 放在轴表中。所以我希望循环/触发器少插入 1 个。 所以如果train_information表有20个车轴。我希望轴表显示 19 等。

最佳答案

您可以将以下触发器作为

delimiter //
create trigger train_information_ins after insert on train_information
for each row 
begin
 declare x int ;
 if(new.number_of_axies >  0 ) then
   set x = 1 ;
   while x < new.number_of_axies do
     insert into axle (train_id,axle)
     values
     (new.train_id,x);
     set x=x+1;
    end while ;
  end if ;
end;//

delimiter ;

关于mysql - 插入后在触发器中循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30164606/

相关文章:

mysql - Ansible:删除多个数据库 MySQL 时出错

MySQL 触发器为 auto_increment 索引生成哈希

mysql - 保留分配给 mysql 中字段的第一个值

php - mysql 左连接和返回已连接和未连接

mysql - SQL 命令默认值

php mysql 未选择表

mysql - 使用表 B 中的内容更新表 A

wpf - 如果没有发生验证错误,如何在工具提示中显示文本框的文本。否则显示验证错误

sql-server - 使用 scope_identity() 触发在 MSSQL 服务器中自动更新 lastModified 列

Mysql触发器不更新连接表