简体   繁体   中英

INSERT TRIGGER AFTER UPDATE ANOTHER TABLE

There are 2 tables orders and pizza. I have to create trigger update_order_pizza which will insert row in table order_pizza after new row is inserted in table order ( or when row is updated).

Code under trigger work when I launch in SQL, but I don't see what changes in table order_pizza after I inserted row in order.

CREATE DEFINER=`root`@`localhost` TRIGGER `update_order_pizza` AFTER INSERT ON `orders` FOR EACH ROW BEGIN
set @orderid = (select max(order_id) from orders);
set @pizzaid = (select max(pizza_id) from pizza);

insert into order_pizza(order_id,pizza_id)
values(@orderid,@pizzaid);
END

I expect to see next

If I insert new order , let;s say order id=36 in table order_pizza should be inserted new record (36,64)

Your code should be using the new variable to reference rows. In addition, your tables should be defining the ids as auto-increment.

So, the code should look more like this:

create trigger `update_order_pizza` after update on `orders` 
for each row
begin

    insert into order_pizza (order_id)
        values (new.order_id);

end;

Alternatively, the pizza_id might be in the orders table, and you may intend:

    insert into order_pizza (order_id, pizza_id)
        values (new.order_id, new.pizza_id);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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