简体   繁体   English

根据列值将行插入另一个表

[英]Insert rows into another table based on column value

I have two tables (shipments and stocks).我有两张桌子(发货和库存)。

shipments table (id, item_id, quantity, expiry_date, status)发货表(id、item_id、数量、expiry_date、状态)

stocks table (id, shipment_id, item_id, quantity, expiry_date)库存表(id、shipping_id、item_id、数量、expiry_date)

status can be either Accepted or Returned . status 可以是AcceptedReturned

I want to create a trigger to insert into stocks table only the shipment items that are Accepted我想创建一个触发器,仅将接受的货件插入到库存表中

This is my code, i don't know how to achieve this.这是我的代码,我不知道如何实现。

DELIMITER //
CREATE TRIGGER insert_stocks AFTER INSERT ON shipments
FOR EACH ROW
BEGIN
 IF shipments.status = 'Accepted' THEN
   INSERT INTO stocks (shipment_id, item_id, quantity, expiry_date)
   VALUES (NEW.shipments, NEW.item_id, NEW.quantity, NEW.expiry_date);
 END IF;
END //
DELIMITER ;

Thanks for the help.谢谢您的帮助。

You have the right idea, but when checking the status of the new row you should use the NEW keyword, like you've done in the insert statement.您的想法是正确的,但是在检查新行的状态时,您应该使用NEW关键字,就像您在insert语句中所做的那样。

Additionally, the shipment ID should be takes from NEW.id , not NEW.shipments (which doesn't exist).此外,货件 ID 应取自NEW.id ,而不是NEW.shipments (不存在)。

IF NEW.status = 'Accepted' THEN
   INSERT INTO stocks (shipment_id, item_id, quantity, expiry_date)
   VALUES (NEW.id, NEW.item_id, NEW.quantity, NEW.expiry_date);
END IF;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM