一尘不染

在过程中指定两次表,该如何解决?

sql

程序是:

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

如何解决?


阅读 121

收藏
2021-05-16

共1个答案

一尘不染

我认为您想要一个相关的子查询:

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
2021-05-16