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

问题描述

我在 UPDATE 中使用子查询:

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))) );

我的问题是,如果子查询没有返回行会发生什么?它会使用 null 进行更新吗?

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

其次,有没有更好的方法来写这个.我基本上是从 tableB 更新 tableA 中的三个字段,但只有在三个字段中的任何一个不同时才会更新.

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.

推荐答案

是的——你可以这样测试:

Yes-- you can test this like:

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

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

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

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

数据库会产生错误.

其次,有没有更好的方法写这个.我基本上在更新表B中表A中的三个字段,但更新应该只发生在这三个字段中的任何一个都是不同的.

凭直觉,我不会担心性能.如果你真的想避免更新,你可以这样写:

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)

WHERE 子句防止使用 NULL 进行更新.

The WHERE clause prevents updates with NULL.

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

08-26 08:51
查看更多