表1中一个字段的值是表2中多个纪录的和,两个表有ID对应,如:表1:
ID1 字段1
1 100
2 80表2:
ID2 字段2
1 20
1 50
1 30
2 40
2 40
我的问题是,如果表2更新了,表1如何更新(不要用循环,数据多了就太慢了)。我想用一个SQL语句做,如下:UPDATE 表1 SET 字段1 = (SELECT SUM(字段2) FROM 表2 WHERE ) WHERE请问,他们的对应关系如何写(WHERE后的语句)?多谢各位!
ID1 字段1
1 100
2 80表2:
ID2 字段2
1 20
1 50
1 30
2 40
2 40
我的问题是,如果表2更新了,表1如何更新(不要用循环,数据多了就太慢了)。我想用一个SQL语句做,如下:UPDATE 表1 SET 字段1 = (SELECT SUM(字段2) FROM 表2 WHERE ) WHERE请问,他们的对应关系如何写(WHERE后的语句)?多谢各位!
//随便这写的,没有试过....^_^
aa int)
Create Table #T2 (ID Int,
bb int)
insert into #t1 select 1,0
union all select 2, 0
insert into #t2 select 1, 20
union all select 1, 50
union all select 1, 30
union all select 2, 40
union all select 2, 40
//以上为插入数据,删除临时表用DROP TABLE #T1
update #t1 set aa=(select sum(bb) from #t2 where #t1.id=#t2.id)
select * from #t1
from
(select id,sum(字段2) b from 表2) a
where id=a.id
没试,你看看
select * into temp from (SELECT id2,SUM(字段2) as f2 FROM 表2 group by id2)//建立tempUPDATE 表1,temp SET 表1.字段1=temp.f2 WHERE 表1.id1=temp.id2//更新表1DROP TABLE temp //删除临时表temp
這有什麼困難的?如果你的前台修改個了表2的某條記錄,保存之後請執行下面SQLvar
CurrentCode,SQL:string;
begin
CurrentCode:=xxx.FieldByName('ID2').AsString;
SQL:=Format(
'UPDATE 表1 SET 字段1 = (SELECT SUM(字段2) FROM 表2 WHERE ID2=%s)WHERE
ID1=%s',[CurrentCode,CurrentCode]); 執行SQL語句;end;======================================================
如果在解發器內:begin
declare @CurrentCode varchar(100),
select @CurrentCode=ID2 from deleted UPDATE 表1 SET 字段1 = (SELECT SUM(字段2) FROM 表2 WHERE ID2=@CurrentCode)WHERE
ID1@CurrentCode
end上面的代碼沒有在delphi和sql analizer內運行, 可能有語法錯誤,但思路正确!