Mysql

更新觸發器插入循環後如何執行 MYSQL?

  • February 11, 2018

我有3個mysql表,一個叫batches,一個叫base_formula,一個叫raw_materials_stock

我想對錶執行更新後觸發器,以根據batches表中的資訊將資訊插入raw_materials_stockbase_formula中。

批次表

batch_id、complete_dt、base_id

基本配方表

base_id、raw_material_id、百分比

原材料庫存表

batch_id,raw_material_id,use_date,數量

批量觸發

IF OLD.complete_dt is NULL and NEW.complete_dt is not null and (select b.raw_material_id from base_formula b where b.base_id=new.base_id) is not null  THEN 

INSERT INTO raw_materials_stock (batch_id,raw_material_id,use_date,quantity) 
VALUES(
new.batch_id,
(select b.raw_material_id from base_formula b where b.base_id=new.base_id),
now(),
(select ((new.volume/100)*b.percent)*-1 from base_formula b where b.base_id=new.base_id)); 

END IF

問題

我遇到的這個問題是base_formula表格有超過 1 行相同base_id。如何使用循環將所有相同的行插入base_idraw_material_stock中?

您可以重組您的查詢

INSERT INTO raw_materials_stock 
 (batch_id,raw_material_id,use_date,quantity) 
   SELECT 
      new.batch_id, 
      b.raw_material_id, 
      now(), 
      ((new.volume/100)*b.percent)*-1 
   from base_formula b where b.base_id=new.base_id;

引用自:https://dba.stackexchange.com/questions/197077