简体   繁体   English

具有自连接功能的Sybase SQL更新

[英]Sybase SQL update with self-join

What's the right syntax in Sybase SQL to do an update with a self join? Sybase SQL中使用自连接进行更新的正确语法是什么? Eg assuming you have the below table (#tmptbl): 例如,假设您具有下表(#tmptbl):

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

I want to overwrite the amounts on 2010-12-31 with the amount values from 2010-12-30. 我想用2010-12-30的金额值覆盖2010-12-31的金额。

I feel like writing something like this: 我感觉像这样写:

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' 

But it doesn't look like Sybase accepts an alias in the 'update <>' clause. 但是看起来Sybase在'update <>'子句中似乎不接受别名。 What's the proper way of doing this? 这样做的正确方法是什么?

Thanks! 谢谢!

This works: 这有效:

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

If you leave out the alias of the table you are updating, ie set amount = new.amount then Sybase associates the table you are updating with the first matching table in the from clause, so in that case for your update to work you'd need the from to read from #tmptbl new, #tmptbl old . 如果省略了要更新的表的别名,即set amount = new.amount则Sybase会将要更新的表与from子句中的第一个匹配表相关联,因此在这种情况下, set amount = new.amount更新set amount = new.amount需要from来读取from #tmptbl new, #tmptbl old

Output: 输出:

 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 

Have you tried 你有没有尝试过

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' 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM