请教一个SQL语句的问题(200分相送)(200分)

  • 主题发起人 主题发起人 jjweb
  • 开始时间 开始时间
J

jjweb

Unregistered / Unconfirmed
GUEST, unregistred user!
表TABLE1
字段 userid type mount
表TABLE2
字段 userid aa
我想写个SQL语句,做以下工作
找TABLE1里 TYPE 为 M 的,在TABLE2里找到相应的USERID,增加AA=AA+MOUNT

我曾经写了以下语句,
update table2 set aa=aa+table1.mount
from (select * from table1 where type=m) as t1,table1
where table2.userid=t1.userid
但只把table1里最后一个TYPE=M的MOUNT加到了TABLE2里,不知道是为什么?
请各位兄弟帮忙解决!


 
我觉得用游标可能好些
 
update一次只能操作一条的,就是你那最后一条,要达到你的要求,可以用一个循环:
代码:
for i:=1 to table.recordcount do
.........
 
试一下

update table2 set aa=aa+table1.mount
from table1,table2 where table2.userid=table1.userid and table1.type='m'
 
update table2 set aa=aa+table1.mount
from table1
where table1.userid=table2.userid and type='m'
你的写法虽然繁,但也可以的,只需要再加一个条件 and table1.userid=table2.userid
 
应该用游标,update一次只能操作一条的
DECLARE updata_cursor CURSOR
FOR update table2 set aa=aa+table1.mount
from (select * from table1 where type=m) as t1,table1
where table2.userid=t1.userid
OPEN updata_cursor
FETCH NEXT FROM updata_cursor
 
我倒,谁说Update一次只能操作一条
 
update table2 set aa=aa+table1.mount
from table1
where type='m' and table1.userid=table2.userid
 
update 可以更新任意条数的记录。你的语句里有错误阿!
下面的语句可以完成你的工作!
update table2 set aa=aa+table1.mount
from table1,table2 where type='M' and table1.userid=table2.userid
祝你好运。
 
我看了大家说的办法,我用了以下语句,还是只替换了一条记录
update table2 set aa=aa+mount
from table2,table1
where table1.type='m' and table2.userid=table1.userid
但我用以下语句看,确实可以看到有2条符合条件
select u.userid,u.balance,e.userid,e.price,e.balance_status
from table2 u,table1 e
where e.type='m' and u.userid=e.userid
请大家告诉我,为什么啊!
 
忘记说一个重要问题了,在TABLE1里,USERID是有重复的,在TABLE2里,USERID是保证唯一的
 
update table2 a
set
aa=aa+b.balance
from
(select u.userid,u.balance,e.userid,e.price,e.balance_status
from table2 u,table1 e
where e.type='m' and u.userid=e.userid) b
 
找到要更新的记录很容易,难得是要更新成什麽(table1.mount)
试试吧,可能不能用
update table2 set aa=aa+table1.mount
from table1 join table2
on table2.userid in(select userid from table1 where type='m')
and table2.userid=table1.userid
 
update t2 t set t.aa=t.aa+(select sum(mount) from t1 where type='M' and userid=t.userid);
 
X的, 这样肯定可以的,再不行用游标了
update table2 set aa=aa+table1.mount
from table1 where table1.type='m' and table1.userid=table2.userid
 

Similar threads

S
回复
0
查看
3K
SUNSTONE的Delphi笔记
S
S
回复
0
查看
2K
SUNSTONE的Delphi笔记
S
I
回复
0
查看
435
import
I
D
回复
0
查看
1K
DelphiTeacher的专栏
D
D
回复
0
查看
1K
DelphiTeacher的专栏
D
后退
顶部