[英]How to update table based from two different tables in php MySQL?
我有3张桌子的预订,订单和库存。 在预订中,我有订单(例如2个苹果和一个橘子)。(reservation.confirmation = orders.confirmation)。 当保留.status更改为“已交付”时,我想更新苹果和橙库存.sold
reservation
---------------------------
confirmation | status
EX-10 pending
orders
---------------------------
confirmation | product | qty
EX-10 apple 2
EX-10 orange 1
inventory
---------------------------
id | nameofproduct | sold
1 apple -->update to 2
2 orange -->update to 1
到目前为止,这里是我的代码。
$confirmation = $_POST['confirmation'];
$status=$_POST['status'];
mysql_query("UPDATE reservation SET status='$status' WHERE reservation_id='$roomid'");
if ($status=='Delivered')
{
mysql_query("UPDATE inventory SET sold = (SELECT qty FROM orders where confirmation='$confirmation') where nameofproduct=(SELECT prduct FROM orders where confirmation='$confirmatioin')");
}
请帮助进行正确的查询。 谢谢
您听说过TRIGGERS
吗? 请参阅: http : //www.sitepoint.com/how-to-create-mysql-triggers/
我已经为您提供了想要的东西,但我没有对其进行检查,因此可能有错误,如果您有任何问题,请告诉我。
DELIMITER $$
CREATE TRIGGER inventory
AFTER UPDATE ON reservation FOR EACH ROW
BEGIN
DECLARE finished INT DEFAULT 0;
DECLARE product VARCHAR(200); -- SHOULD BE THE SAME TYPE AND LENGTH AS order.product
DECLARE qty INT; -- SHOULD BE THE SAME TYPE AND LENGTH AS order.qty
DECLARE orders_cursor CURSOR FOR SELECT o.product, o.qty FROM orders o WHERE o.confirmation = NEW.confirmation;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
IF (NEW.status = 'delivered') THEN
open orders_cursor;
get_orders: LOOP
FETCH orders_cursor INTO product, qty;
IF finished = 1 THEN
LEAVE get_orders;
END IF;
-- UPDATE INVENTORY
UPDATE inventory i SET i.sold = qty WHERE i.nameofproduct = product;
END LOOP get_orders;
close orders_cursor;
END IF;
END
$$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.