update 更新语句关联两张表为什么加exists

如题所述

oracle吧,

    sqlserver支持update from的语法

比如:

update a set a.value = b.data from b where a.id = b.id

可以看出,其实a和b做了一次内连接;

    而oracle不支持update from的语法,那再来看看oracle的写法:

update a set a.value = (select b.data from b where a.id = b.id) where exists(select 1 from b where a.id = b.id)

或者用in:

update a set a.value = (select b.data from b where a.id = b.id) where a.id in (select b.id from b)

    如果我们把exists或者in的部分去掉:

update a set a.value = (select b.data from b where a.id = b.id)

再来点数据:

a表:

id value

1  'abc'

2  'def'

b表:

id data

1  '123'

3  '456'

那么我们用不带exists和in的update(update a set a.value = (select b.data from b where a.id = b.id))会怎样?

A表:

id value

1  '123'

2  null

这不会是你要的吧?!

所以:如果使用关联表进行更新,并且其它表和被更新的表也要关联时(此处埋伏了一个条件未讲可以自己思考试验),则需要带上exists或in的条件。

温馨提示:答案为网友推荐,仅供参考
相似回答