SQL:如果某种记录不在同一个表中,则更新记录

时间:2016-09-08 01:10:01

标签: mysql sql

我想仅在表中不存在某个其他记录时才更新表的某个记录。

我尝试了类似于以下的SQL。

update mytable
     set val = 'someval'
     where id = 'someid' and
           0 = (select count(*) from mytable where col='val2');

此操作失败并出现以下错误。

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

只有一个进程正在更新此表,因此不需要保留操作的原子性。

我知道我可以使用两个SQL查询来执行此操作,但有一种方法可以在单个查询中执行此操作吗?

3 个答案:

答案 0 :(得分:2)

因为您指的是同一个表格,所以最好的方法是使用LEFT JOIN

update mytable t left join
       mytable t2
       on t2.col = 'val2'
    set val = 'someval'
    where t.id = 'someid' and t2.col is null;

答案 1 :(得分:1)

有几种方法可以做到这一点。这是使用带有not exists的子查询的一个选项:

update mytable 
set val = 'someval' 
where id = 'someid' 
  and not exists (
    select 1
    from (select * from mytable) t
    where col = 'val2')

使用子查询会绕过您收到的错误。其他方法包括outer join null次检查或使用not in - 取决于数据。

答案 2 :(得分:0)

尝试这个:

UPDATE mytable SET val = 'someval' 
WHERE id = 'someid' AND col <> 'val2'