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

时间:2018-12-09 00:09:40

标签: mysql sql

尝试运行过程时收到此消息:

enter image description here

过程是:

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

如何解决?

1 个答案:

答案 0 :(得分: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