且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

自动更新数据库Mysql中的库存

更新时间:2023-02-08 17:52:13

从技术意义上讲,您所要求的不是关系数据库时的关系".这样的关系就像有一个表引用另一个表的键",例如,将一个具有客户地址的表与另一个具有客户订单的表相关联.无论如何,这超出了您的要求,因此无法回答您的问题,您可以在应用程序代码或触发器中进行此操作.

What you're asking about isn't technically a "relationship" in the technical sense when referring to relational databases. Such relations are things like having a table that refers to the "key" of another table, for instance relating a table with a customer's address to another table with the customer's order. Anyway, that's beyond the scope of what you asked about so to answer your question, you can do that in the application code or a trigger.

触发器是数据库的功能,在发生INSERT,UPDATE或DELETE时会执行 .

Triggers are features of the database that does something when an INSERT, UPDATE, or DELETE happens.

通过对表/列名进行较小的调整,这样的事情应该可以正常工作

Something like this should work okay with minor adjustments for table/column names:

UPDATE table2 SET inventory = inventory - NEW.qty where id = NEW.id_product;

现在只覆盖INSERT;您将要为Event UPDATE创建另一个触发器,并可能以某种方式处理退货或已取消的订单,但这可能是在应用程序级别而不是触发器中处理的.

Now that only covers an INSERT; you'll want to create another trigger for Event UPDATE and probably somehow handle returned inventory or cancelled orders as well, but that's probably something you'll handle at the application level rather than in a trigger.