通过子查询更新,如果子查询不返回任何行? [英] Update via subquery, what if the subquery returns no rows?

查看:188
本文介绍了通过子查询更新,如果子查询不返回任何行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在UPDATE中使用子查询:

  UPDATE tableA 
SET x,y,z = (SELECT x,y,z
FROM tableB b
WHERE tableA.id = b.id
AND(tableA.x!= bx
OR tableA.y!= by
OR tableA.z!= bz))));我的问题是,如果子查询没有返回任何行,会发生什么?msgctxt@info:whatsthis它会用null来更新吗?



其次,有更好的方法来写这个。我基本上从tableB更新tableA中的三个字段,但更新应该只发生在三个字段中的任何一个不同。

解决方案


如果子查询返回
没有行会发生什么?它会用
nulls更新吗?


是的,你可以这样测试:

 更新YourTable 
set col1 =(select 1 where 1 = 0)

这将填充col1为NULL。如果子查询返回多行,例如:

  update YourTable 
set col1 =(select 1 union select 2)

数据库将产生错误。



< >

其次,有没有更好的方式
写这个。我基本上从tableB,
更新
三个字段在tableA,但更新应该发生,如果
任何三个字段是不同的。


直观地,我不会担心性能。如果你真的希望避免更新,你可以这样写:

  UPDATE a 
SET x = bx, y = by,z = bz
FROM tableA a,tableB b
WHERE a.id = b.id AND(ax≠bx OR ay≠by OR az& bz)

WHERE NULL。


I am using a subquery in an UPDATE:

UPDATE tableA 
SET x,y,z = ( (SELECT x, y, z 
               FROM tableB b
               WHERE tableA.id = b.id
                 AND (tableA.x != b.x
                      OR tableA.y != b.y
                      OR tableA.z != b.z))) );

My question is, what happens if the subquery returns no rows? Will it do an update with nulls?

Secondly, is there a better way to write this. I am basically updating three fields in tableA from tableB, but the update should only happen if any of the three fields are different.

解决方案

what happens if the subquery returns no rows? Will it do an update with nulls?

Yes-- you can test this like:

update YourTable
set col1 = (select 1 where 1=0)

This will fill col1 with NULLs. In case the subquery returns multiple rows, like:

update YourTable
set col1 = (select 1 union select 2)

The database will generate an error.

Secondly, is there a better way to write this. I am basically updating three fields in tableA from tableB, but the update should only happen if any of the three fields are different.

Intuitively I wouldn't worry about the performance. If you really wish to avoid the update, you can write it like:

UPDATE a
SET x = b.x, y = b.y, z = b.z
FROM tableA a, tableB b 
WHERE a.id = b.id AND (a.x <> b.x OR a.y <> b.y OR a.z <> b.z)

The WHERE clause prevents updates with NULL.

这篇关于通过子查询更新,如果子查询不返回任何行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆