首页 > 解决方案 > 如何在使用同一个表过滤数据的表中更新列?

问题描述

我正在尝试在这里更新一列。当我运行 select 语句时,它会给出正确的结果。但我无法更新。这是我正在运行的脚本....

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

标签: mysqlsql

解决方案


MySQL 不允许子查询引用正在更新的表。所以,使用 aleft join代替:

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

我也强烈建议你不要使用not in子查询。当子查询not in中的任何值为NULL. 因此,使用有时不符合您预期的东西只是一种不好的做法。


推荐阅读