2

我有以下查询,当我在子查询中使用不存在的列引用时没有错误。我在子查询中引用的列实际上是正在更新的表中的列。

create table tbl1 (f1 bigint, f2 char(10), f3 integer);
insert into tbl1 values (1, 'aa', 0);
insert into tbl1 values (2, 'bb', 0);
insert into tbl1 values (3, 'cc', 0);
insert into tbl1 values (4, 'dd', 0);

create table temp_tbl (ref_num bigint);
insert into temp_tbl values (1);
insert into temp_tbl values (3);

update tbl1 set f2='ok' where f1 in (select f1 from temp_tbl);
-- 4 records updated

谁能告诉我为什么它没有给出任何错误?无论条件如何,记录都会更新。

我在 Oracle 和 SQLserver 中都试过这个。结果是一样的

4

2 回答 2

0

发生这种情况是因为 SELECT 中的值不仅必须是您从中选择的表中的列,子查询返回的是f1来自外部查询的值,而不是来自temp_tbl.

考虑是否将查询重写UPDATE为:

SELECT  *
FROM    tbl1 
WHERE   f1 IN (select f1 from temp_tbl);

返回的结果实际上是:

执行查询的结果

当您尝试对此类事情进行推理时(并且作为一种正确获取查询的一般好方法!),UPDATE以以下形式编写查询很有用:

UPDATE  T
SET     F2 = 'ok'
FROM    TBL1 T
WHERE   T.f1 IN
        (
            SELECT  F1
            FROM    temp_tbl
        )

通过以这种方式编写它,您可以轻松地注释掉查询的UPDATESET组件,将它们替换为 aSELECT并查看查询将操作的数据集是什么。

于 2019-01-03T11:25:04.690 回答
0

子查询的列引用转到外部表!

update tbl1 set f2='ok' where f1 in (select f1 from temp_tbl);

读作

update tbl1 set f2='ok' where f1 in (select tbl1.f1 from temp_tbl);

限定您的列:

update tbl1 set f2='ok' where f1 in (select temp_tbl.ref_num  from temp_tbl);
于 2019-01-03T11:25:20.583 回答