Can SQL perform calculation on update?
Can SQL perform calculation on update? For instance, the stored product quantity was 5, and after being sold, say 3 items, I want to update the quantity left in the product tables
,
$sql_update = "
UPDATE store_products
SET
product_quantity = ?
WHERE store_products.product_id = ?
";
$result = $connection->run_query($sql_update,array(开发者_JAVA百科
3,
$product->product_id
));
Is it possible?
Yes - to achieve what you describe you need to implement an AFTER UPDATE
trigger.
For details and samples see:
- http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html
- http://www.roseindia.net/sql/trigger/mysql-trigger-after-update.shtml
EDIT - as per comment a sample:
CREATE TRIGGER produpd AFTER UPDATE ON store_products
FOR EACH ROW BEGIN
UPDATE product SET quantity = quantity - NEW.product_quantity WHERE product_id = NEW.product_id;
END;
This trigger needs to be created in your MySQL DB... when you execute the SQL code from your question MySQL invokes this trigger and update the products
table.
精彩评论