sql - 使用自联接更新 Sybase SQL

标签 sql sybase self-join

Sybase SQL 中使用自连接进行更新的正确语法是什么?例如。假设您有下表(#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

我想用 2010 年 12 月 30 日的金额覆盖 2010 年 12 月 31 日的金额。

我想写这样的东西:

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 <>”子句中的别名。这样做的正确方法是什么?

谢谢!

最佳答案

这有效:

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

输出:

 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 

关于sql - 使用自联接更新 Sybase SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4606174/

相关文章:

mysql - 如何使这个缓慢的查询更快

java - 提取 Sybase 数据库的 DDL 语句

sql - 简单的自连接查询性能不佳

mysql - 在MySQL查询中获取表的坐标(行,列)

sql - 每条记录的平均值和前 5 个最大值

SQL 日期查询 - 此条件成立多长时间

java - iBatis 映射 : map a string field into a List<String>

sql - 如何编写 SQL 语句以返回基于 X、Y 和 Z 列的不同记录以及表中 A 列的第一个值

sql - 从数据库表中选择重复条目

sql - 用于 250K+ 字符串的通配符搜索的 Fast(er) 方法