为什么在尝试执行此查询时出现错误:
UPDATE ordersperformers AS t1 SET t1.Status = 1
where not exists (
SELECT 1 FROM ordersperformers
WHERE ordersperformers.Orders_Id = 3
AND (ordersperformers.Status = 1 OR ordersperformers.Status = 2))
AND t1.Orders_Id = 3 AND t1.Users_Id = 5;
为什么MySQL无法意识到我正在使用表ordersperformers
?
错误是:
#1093 - Table 't1' is specified twice, both as a target for 'UPDATE' and as a separate source for data
。
如果执行查询:
UPDATE ordersperformers SET Status = 1
where ordersperformers.Status NOT IN (1,2)
AND Orders_Id = 3;
无论如何它将更新一行:
但是我不需要更新任何行,因为带有Orders_Id = 3
的表具有带有Status = 1
的一行
答案 0 :(得分:2)
如果要使用相同的order_id至少具有一个Status = 1的状态更新Status = 1,则需要使用EXISTS()
。
另外,因为我们确实检查了同一张表,所以需要将其放在sub-query
中(是,在括号内),以避免发生冲突。
您只需要执行以下操作即可:
脚本编辑:
UPDATE ordersperformers as O1
SET O1.Status = 1
where EXISTS
(SELECT 1
FROM (select * from ordersperformers) AS O2
WHERE O1.Orders_Id = O2.Orders_Id
AND O2.Status = 1
)