birdy
birdy

Reputation: 9646

can't specify target table for UPDATE in FROM clause

I am trying to execute the following query:

update table3 d set status = 'Complete'
where d.id in 
(
    select b.id from table1 a, table3 b, table2 c
    where a.id = b.table1_id
    and c.id = b.table2_id
    and c.examId = 16637                 -- will be passed in by user
    and a.id in (46,47,48,49)            -- will be passed in by user
);

So, I'm trying to update multiple rows of table3.

table3 is a join table between table1 and table2.

Upvotes: 1

Views: 7090

Answers (1)

John Woo
John Woo

Reputation: 263743

wrap it in a subquery, (thus creating a temporary table for the result). I'm also recommending to use ANSI SQL-92 format.

update table3 d 
set    status = 'Complete'
where  d.id in 
(
    SELECT ID
    FROM
    (
        select  b.id 
        from    table1 a 
                INNER JOIN table3 b
                    ON a.id = b.table1_id
                INNER JOIN table2 c
                    ON c.id = b.table2_id
        where   c.examId = 16637 and 
                a.id in (46,47,48,49) 
    ) xx
);

or by using JOIN

update  table3 d 
        INNER JOIN
        (
            SELECT ID
            FROM
            (
                select  b.id 
                from    table1 a 
                        INNER JOIN table3 b
                            ON a.id = b.table1_id
                        INNER JOIN table2 c
                            ON c.id = b.table2_id
                where   c.examId = 16637 and 
                        a.id in (46,47,48,49) 
            ) xx
        ) y ON d.id = y.id
set status = 'Complete'

Upvotes: 3

Related Questions