我有一个sql update查询,如下所示:
update #tree c
set treetop=p.treetop,
treeptag=p.treeptag,
adjust= 'a2a'
from #tree p ,#regions r
where c.treeptag=''
and c.xsreg=r.Region
and c.xsreg <> c.reg
and c.tradedate=p.tradedate
and p.treeaotag=replace(r.srvid+':'+c.tradedate+':'+c.litag,' ','')
我试图在不使用“fromlist”的情况下使用连接编写查询,如下所示:
update #tree c
set treetop=(select p.treetop from #tree p ,#regions r
where c.treeptag=''
and c.xsreg=r.Region
and c.xsreg <> c.reg
and c.tradedate=p.tradedate
and p.treeaotag=replace(r.srvid+':'+c.tradedate+':'+c.litag,' ','')),
treeptag=(select p.treeptag from #tree p ,#regions r
where c.treeptag=''
and c.xsreg=r.Region
and c.xsreg <> c.reg
and c.tradedate=p.tradedate
and p.treeaotag=replace(r.srvid+':'+c.tradedate+':'+c.litag,' ','')),
adjust= 'a2a'
where exists (select 1 from #tree p ,#regions r where c.treeptag=''
and c.xsreg=r.Region
and c.xsreg <> c.reg
and c.tradedate=p.tradedate
and p.treeaotag=replace(r.srvid+':'+c.tradedate+':'+c.litag,' ',''))
但是上面的查询似乎返回了错误的行数;任何建议都会有所帮助。
答案 0 :(得分:0)
翻译是正确的,因此行数应完全相同。如果表很小,请使用DDL和示例数据插入更新问题。否则,这些会返回什么?
select count(1)
from #tree c, #tree p ,#regions r
where c.treeptag=''
and c.xsreg=r.Region
and c.xsreg <> c.reg
and c.tradedate=p.tradedate
and p.treeaotag=replace(r.srvid+':'+c.tradedate+':'+c.litag,' ','')
和
select count(disctint c.id) -- or whatever the unique key on #tree is
from #tree c, #tree p ,#regions r
where c.treeptag=''
and c.xsreg=r.Region
and c.xsreg <> c.reg
and c.tradedate=p.tradedate
and p.treeaotag=replace(r.srvid+':'+c.tradedate+':'+c.litag,' ','')
两者如何与更新相比?我原以为它会与第二次计数相符。
对于它的价值,它是2012年,所以使用适当的ANSI连接:
update c
set treetop=p.treetop, treeptag=p.treeptag, adjust='a2a'
from #tree c
join #tree p on c.tradedate=p.tradedate
join #regions r on c.xsreg=r.Region
where c.treeptag='' and c.xsreg <> c.reg
and p.treeaotag=replace(r.srvid+':'+c.tradedate+':'+c.litag,' ','')
您的某些条件直接针对c
,那么为什么要将它们纳入子查询?
update #tree c
set treetop =(select p.treetop
from #tree p
join #regions r on c.xsreg=r.Region
where c.tradedate=p.tradedate
and p.treeaotag=replace(r.srvid+':'+c.tradedate+':'+c.litag,' ','')),
treeptag=(select p.treeptag
from #tree p
join #regions r on c.xsreg=r.Region
where c.tradedate=p.tradedate
and p.treeaotag=replace(r.srvid+':'+c.tradedate+':'+c.litag,' ','')),
adjust ='a2a'
where c.treeptag='' and c.xsreg <> c.reg and -- << these two
exists (select 1
from #tree p
join #regions r on c.xsreg=r.Region
where c.tradedate=p.tradedate
and p.treeaotag=replace(r.srvid+':'+c.tradedate+':'+c.litag,' ',''))