我有下表。
order_id code value
1 sub_total 5.00
1 shipping 5.00
1 total 10.00
2 sub_total 3.00
2 shipping 6.00
2 total 9.00
有时sub_total将需要更新(例如添加产品),并且还需要更新总数。我创建了一个Trigger来更新sub_total。我如何根据sub_total和运费来更新总数?
我尝试过以下方法:
CREATE TRIGGER after_order_product_update AFTER UPDATE ON order_product FOR EACH ROW
BEGIN
UPDATE `order_total`
SET `value` = NEW.`total` WHERE `order_id` = NEW.`order_id` AND `code` = 'sub_total';
UPDATE `order_total`
SET `value` = (SELECT `value` FROM `order_total` WHERE `code` = 'shipping' AND `order_id` = NEW.`order_id`) + (SELECT `value` FROM `order_total` WHERE `code` = 'sub_total' AND `order_id` = NEW.`order_id`) WHERE `code` = 'total' AND `order_id` = NEW.`order_id`;
END;
这里我收到一个“你不能在FROM子句中为更新指定目标表'oc_order_total'错误号:1093”
CREATE TRIGGER after_order_product_update AFTER UPDATE ON order_product FOR EACH ROW
BEGIN
DECLARE SBvalue VARCHAR(32);
DECLARE SHIPvalue VARCHAR(32);
UPDATE `order_total` SET `value` = NEW.`total` WHERE `order_id` = NEW.`order_id` AND `code` = 'sub_total';
SET SBvalue = (SELECT `value` FROM `order_total` WHERE `code` = 'sub_total' AND `order_id` = NEW.`order_id`);
SET SHIPvalue = (SELECT `value` FROM `order_total` WHERE `code` = 'shipping' AND `order_id` = NEW.`order_id`);
UPDATE `oc_order_total` SET `value` = `SBvalue` + `SHIPvalue` WHERE `code` = 'total' AND `order_id` = NEW.`order_id`;
END;
这里我收到“子查询返回超过1行”错误。
答案 0 :(得分:0)
SET SBvalue = (SELECT `value` FROM `order_total` WHERE `code` = 'sub_total'
AND `order_id` = NEW.`order_id` LIMIT 1);
SET SHIPvalue = (SELECT `value` FROM `order_total` WHERE `code` = 'shipping'
AND `order_id` = NEW.`order_id` LIMIT 1);
为第二个查询错误提供限制1 ..
希望这有帮助
答案 1 :(得分:0)
BEGIN
UPDATE `order_total`
SET `value` = (
(SELECT `value` FROM (
SELECT `value` FROM `oc_order_total`
WHERE `code` = 'sub_total' AND `order_id` = NEW.`order_id`)
AS mySubTotalTable
WHERE `order_id` = NEW.`order_id`) +
(SELECT `value` FROM (
SELECT `value` FROM `oc_order_total`
WHERE `code` = 'shipping' AND `order_id` = NEW.`order_id`)
AS myShippingTable
WHERE `order_id` = NEW.`order_id`))
WHERE `code` = 'total' AND `order_id` = NEW.`order_id`;
END