问题描述
UPDATE ordersperformers op
SET op.Status = 1
WHERE op.Status = 0 AND
op.Orders_Id = @v_order_id AND
op.Users_Id = @v_user_id AND
EXISTS (SELECT 1
FROM orders o
WHERE o.id = op.Orders_Id AND
Now() <= DATE_SUB(o.DeliveryDate, INTERVAL 2 HOUR) AND
o.Status = 0
);
我更改/修复了其他一些问题:
- 表别名使查询更易于编写和阅读。
- 反引号使查询更难写和读。
- 仅在要更新的表上的条件应该在外部
WHERE
,而不是内部WHERE
。 - 在
EXISTS
子查询中设置变量根本没有意义。EXISTS
测试 行 是否存在。从逻辑上讲,它无需评估即可执行SELECT
。
解决方法
程序是:
BEGIN
DECLARE v_user_id INT DEFAULT 0;
DECLARE v_order_id INT DEFAULT 0;
DECLARE v_min_price INT DEFAULT 0;
UPDATE `ordersperformers` SET `ordersperformers`.`Status` = 1
WHERE EXISTS (
SELECT
@v_min_price = MIN(`ordersperformers`.`DeliveryPrice` + `ordersperformers`.`Price`),@v_user_id = `ordersperformers`.`Users_Id` = @v_user_id,@v_order_id =`ordersperformers`.`Orders_Id`
FROM `ordersperformers`
INNER JOIN
`orders` ON `orders`.`Id` = `ordersperformers`.`Orders_Id` WHERE
NOW() <= DATE_SUB(`orders`.`DeliveryDate`,INTERVAL 2 HOUR) AND `orders`.`Status` = 0 AND `ordersperformers`.`Status` = 0
) AND `ordersperformers`.`Orders_Id` = @v_order_id AND `ordersperformers`.`Users_Id` = @v_user_id;
END
如何解决?