简体   繁体   中英

Specifying same table in subquery in main UPDATE statement

I'm getting error below for second query at the bottom. Any idea idea why?

Thanks

ERROR: Error Number: 1093

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

WORKS:

INSERT INTO menus
(name, controller, parent)
VALUES
('A', 'B', (SELECT id FROM menus menus_alias WHERE SHA1(menus_alias.id) = '1'))

BOTH DON'T WORK:

UPDATE menus SET
parent = (SELECT id FROM menus menus_alias WHERE SHA1(menus_alias.id) = '1')
WHERE SHA1(id) = '5'

UPDATE menus menus_alias SET
menus_alias.parent = (SELECT id FROM menus WHERE SHA1(id) = '1')
WHERE SHA1(menus_alias.id) = '5'

Checked out these:

and some others

Use JOIN

UPDATE menus m1 JOIN menus m2
    ON SHA1(m1.id) = '5' AND SHA1(m2.id) = '1'
   SET m1.parent = m2.id

You can try this

UPDATE menus SET
parent =(
    SELECT id FROM (
        SELECT id FROM menus
    ) AS x 
    WHERE SHA1(id) = '1'
)
WHERE SHA1(menus_alias.id) = '5'

Try this workaround (both queries must be exec in the same mysql session):

SELECT 
    id INTO @za_id 
FROM 
    menus 
WHERE 
    SHA1(id) = '1';

UPDATE menus 
    SET parent = @za_id
WHERE 
    SHA1(id) = '5'; 

Also you are trying to update a table with values from the same table and since mysql doesn't know that the data selected is from different records then the records that should be updated it throws an error.

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