简体   繁体   中英

How to combine UPDATE query with subquery?

In my Mysql database I want to update a field fup for all records which I found using this select statement:

SELECT ic.hash
FROM incompany as ic, app
WHERE ic.id = app.ic_id;

So I created the following combined query:

UPDATE incompany
SET fup = 'x' 
WHERE hash IN (SELECT ic.hash
FROM incompany as ic, app
WHERE ic.id = app.ic_id);

But this query gives me the following error:

You can't specify target table 'incompany' for update in FROM clause

Does anybody know how I can make this work? All tips are welcome!

You seem to want a condition on two columns, so this is a bit tricky. If I follow the logic correctly:

UPDATE incompany ic JOIN
       (SELECT DISTINCT ic.hash
        FROM incompany ic JOIN
             app
             ON ic.id = app.ic_id 
       ) ica
       ON ica.hash = ic.hash
    SET fup = 'x' ;

You do not need a subquery. You might use INNER JOIN to set the criteria to link the incompany table to the app table and to the another alias for incompany table.

UPDATE incompany I 
INNER JOIN app A ON I.id = A.ic_id
INNER JOIN incompany I2 ON I.hash = I2.hash
SET I.fup = 'x' 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM