为什么“where where”在这两个例子中的功能不同?

时间:2013-07-12 20:27:19

标签: sql-server tsql

对于该示例,Table1定义为 (id int,address varchar(100))

将更新表格中的每个值:

create table #test (id int, address varchar(100))

insert into #test (id, address)
values (5, 'test address')

update Table1
set
    address = (select top 1 address from #test)
where exists (select 1 from #test t where id = t.id)

只会更新id = 5的条目:

create table #test (id2 int, address varchar(100))

insert into #test (id2, address)
values (5, 'test address')

update Table1
set
    address = (select top 1 address from #test)
where exists (select 1 from #test t where id = t.id2)

唯一的区别似乎是一个临时表具有与源表匹配的ID而另一个不具有。为什么会这么重要?还是有更微妙或更明显的事情发生在这里?

1 个答案:

答案 0 :(得分:2)

显然,这总是回归真实?

select 1 from #test t where id = t.id  

独立ID使用#test

的t

在第二个t中没有ID,因此它将树查找到Table1

消息是不要使用含糊不清的名字
如果名称不明确,则包括表(或别名)名称

为什么你会以这种方式存在?

相关问题