简体   繁体   中英

How can I update a column in a table where I am using the same table to filter the data?

I am trying to update a column here. When I run select statement, it gives proper results. But I am not able to update. Here is the script that I am running....

update table1
  set col1 = 0
where col1 = 1 and col2 not in (select col3 from table1);

MySQL does not allow subqueries to reference the table being updated. So, use a left join instead:

update table1 t1 left join
       table1 tt1
       on t1.col2 = tt1.col3
    set col1 = 0
where t1.col1 = 1 and tt1.col3 is null;

I also strongly advise you not to use not in with subqueries. The not in doesn't usually do what you intend when any value in the subquery is NULL . Hence, it is just a bad practice to use something that sometimes does not do what you intend.

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