简体   繁体   中英

Updating table column based on other table column

I want to update table cases_proceedings but it will check some criteria for this in the other table cases_attach_files ie

SELECT cp.sno FROM cases_proceedings cp, cases_attach_files cf 
WHERE cp.`case_sno` = cf.`case_sno` AND cf.page_lbl_sno = 10 AND 
cp.`is_decided` = 0

But when i want to update the first table value and search the sno of the first table by using the IN operation with subquery like this:

UPDATE cases_proceedings 
     SET `is_decided` = 1 
WHERE sno IN(SELECT cp.sno FROM cases_proceedings cp, cases_attach_files cf 
WHERE cp.`case_sno` = cf.`case_sno` AND cf.page_lbl_sno = 10 AND 
cp.`is_decided` = 0);

It shows an error:

Error Code: 1093
You can't specify target table 'cases_proceedings' for update in FROM clause

i don't know how to fix this?

One workaround here is to wrap the subquery in another subquery:

UPDATE cases_proceedings 
SET is_decided = 1 
WHERE sno IN
(
    SELECT sno
    FROM
    (
        SELECT cp.sno
        FROM cases_proceedings cp
        INNER JOIN cases_attach_files cf 
            ON cp.case_sno = cf.case_sno AND
               cf.page_lbl_sno = 10 AND
               cp.is_decided = 0
    ) t
);

The extra subquery works around the error because it forced MySQL to materialize the subquery containing the joins.

According to documentation , In MySQL, you can't modify the same table which you use in the SELECT part.

You can either wrap it in subquery or joining both tables as shown below:

UPDATE  cases_proceedings cp
        INNER JOIN cases_attach_files cf
            ON cp.case_sno = cf.case_sno
                AND cf.page_lbl_sno = 10 
                AND cp.is_decided = 0
SET     cp.is_decided = 1 

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