Skip to content
Advertisement

Insert trigger subtract value from another table

I am a newbie at sql. I made a php website that user can make item purchases. And now I want to make a trigger for when a receipt is created, it subtracts the quantity in the item stock table with the quantity sold in the receipt.

The sql script above is for the receipt table. The id for this table is auto generated using autoincrement. One ReceiptID can contain many items. So I am using a composite of ReceiptID and ItemID sold as the primary key. And here is the Script for the table.

I have been trying to make the trigger on my own, but I am still quite unfimiliar with sql triggers. Here is what I came up with.

Thank you for your help in advance.

Advertisement

Answer

I don’t think the trigger needs to be quite so complicated as you can access the values required directly by prefixing the column name with NEW

Using a slightly simplified schema ( remove FK dependency upon Supplier table )

And populated a single Product in the item table

And an initial record in the receipt table

and a subsequent second record ( showing used sql )

The trigger has updated the item table accordingly

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement