1

Why I got an error when try to execute this query:

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;

Why MySQL does not realize that I work with table ordersperformers?

Error is:

#1093 - Table 't1' is specified twice, both as a target for 'UPDATE' and as a separate source for data.

If execute query:

UPDATE ordersperformers SET Status = 1 
where  ordersperformers.Status NOT IN (1,2)
AND Orders_Id = 3;

It will update anyway one row:

enter image description here

But I dont need update any rows cause table with Orders_Id = 3 has one row with Status = 1

POV
  • 11,293
  • 34
  • 107
  • 201
  • I faced with this problem it a lot of my queries, I dont have problems if run this query in SQL Database – POV Dec 09 '18 at 18:37
  • Possible duplicate of [Table is specified twice, both as a target for 'UPDATE' and as a separate source for data in mysql](https://stackoverflow.com/questions/44970574/table-is-specified-twice-both-as-a-target-for-update-and-as-a-separate-source) – Himanshu Dec 09 '18 at 18:39
  • use `select * from table` inside that query after update rather `as table` in order to avoid this mysql confusion as per the reference link above – Himanshu Dec 09 '18 at 18:41
  • Can you show this? – POV Dec 09 '18 at 19:04
  • please refer the link in the above comment check the corrected answer hope that helps – Himanshu Dec 09 '18 at 19:12
  • I dont understend how apply this to my query – POV Dec 09 '18 at 19:16
  • @OPV Have you thought that maybe you did not make clear which rows need to be updated and which not? – forpas Dec 09 '18 at 19:17

1 Answers1

2

You need to use EXISTS() if you want to update Status=1 with same order_id has at least one Status=1. Also because we do check with the same table you need put it to sub-query (yes, inside the bracket) to avoid conflict.

Simply you need to do something like this :

SCRIPT EDITED:

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
             )
Zeki Gumus
  • 1,484
  • 7
  • 14