首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Sybase SQL update with self-join

Sybase SQL update with self-join
EN

Stack Overflow用户
提问于 2011-01-06 00:00:55
回答 2查看 11.8K关注 0票数 2

Sybase SQL中使用自联接执行更新的正确语法是什么?例如,假设您有下表(#tmptbl):

代码语言:javascript
复制
account | client  |amount | date
-------------------------------------
ACT1    | CLIENTA | 12    |2010-12-30
ACT2    | CLIENTB | 5     |2010-12-30
ACT1    | CLIENTA | 17    |2010-12-31
ACT2    | CLIENTB | 6     |2010-12-31

我想用2010-12-30的金额值覆盖2010-12-31的金额。

我想写这样的东西:

代码语言:javascript
复制
update old
set old.amount = new.amount
from #tmptbl old,  #tmptbl new
where 
/*filter old*/
old.account = 'ACT1' 
and old.date = '2010-12-30' 
and old.client = 'CLIENTA' 
/* self-join new and old*/
and old.account = new.account 
and old.client = new.client 
/* filter new */
and new.date = '2010-12-31' 

但看起来Sybase不接受“update<>”子句中的别名。这样做的正确方式是什么?

谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-01-06 00:14:18

这是可行的:

代码语言:javascript
复制
update #tmptbl
set old.amount = new.amount
from #tmptbl old,  #tmptbl new
where 
/*filter old*/
old.account = 'ACT1' 
and old.date = '2010-12-30' 
and old.client = 'CLIENTA' 
/* self-join new and old*/
and old.account = new.account 
and old.client = new.client 
/* filter new */
and new.date = '2010-12-31' 
go

如果省略了要更新的表的别名,即set amount = new.amount,则Sybase会将正在更新的表与from子句中的第一个匹配表相关联,因此在这种情况下,要使更新起作用,您需要使用from读取from #tmptbl new, #tmptbl old

输出:

代码语言:javascript
复制
 account     client     amount     date             
 ----------  ---------  ---------  ---------------- 
 ACT1        CLIENTA    12         30/12/2010 00:00 
 ACT2        CLIENTB    5          30/12/2010 00:00 
 ACT2        CLIENTB    6          31/12/2010 00:00 
 ACT1        CLIENTA    12         31/12/2010 00:00 
票数 4
EN

Stack Overflow用户

发布于 2011-01-06 00:12:43

你试过了吗?

代码语言:javascript
复制
update #tmptbl 
set amount = new.amount
from #tmptbl old,  #tmptbl new
where 
/*filter old*/
old.account = 'ACT1' 
and old.date = '2010-12-30' 
and old.client = 'CLIENTA' 
/* self-join new and old*/
and old.account = new.account 
and old.client = new.client 
/* filter new */
and new.date = '2010-12-31' 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4606174

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档