繁体   English   中英

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

[英]SQL: update a record if a certain kind of a record is not in the same table

我只想在表中还不存在某些其他记录的情况下更新表的某个记录。

我尝试了类似于以下的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查询来执行此操作,但是有没有办法在单个查询中执行此操作?

因为您引用的是同一张表,所以最好的方法是使用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;

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

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

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

尝试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM