【问题标题】:update with join in oracle sql在 oracle sql 中加入更新
【发布时间】:2019-12-07 13:46:59
【问题描述】:
我想更新 table1 的列,但我应该只更新另一个表中条件为真的记录
类似这样的东西,但我不知道如何在 Oracle SQL 中实现这个目的
update table1
join table2 on table1.msg_id = table2.id
set table1.index = table1.index-1
where table1.index > 10 and table2.type = 'myType'
【问题讨论】:
标签:
sql
oracle
sql-update
【解决方案1】:
我会将其写为任何数据库中的exists 子查询:
update table1 t1
set index = t1.index - 1
where table1.index > 10 and
exists (select 1
from table2
where t2.id = t1.msg_id and
t2.type = 'myType'
);
join 表示您将在table1 的更新中使用来自table2 的数据。相反,您只想在满足特定条件时更改一行中的值。
【解决方案2】:
Oracle 不支持这种语法(叹气)。
对于您的用例,您可以使用带有相关子查询的 not exists 条件:
update table1
set table1.index = table1.index - 1
where
table1.index > 10
and exists (
select 1 from table2 where table1.msg_id = table2.id and table2.type = 'mytype'
)
注意:让您的生活更轻松,不要使用index 作为列名。这是几乎所有 RDBMS 中的保留工作。