这样的sql如何写?

hbgzg3006 2010-07-26 10:46:19

表A
id name agenum
表B
id age
--有没有好的办法把新的age数量赋值给表A的agenum,也就是id是同一个值的B表的数量变化后更新到A表的agenum
update A a set a.agenum=? where a.agenum!=(select count(*) from B b where a.id =b.id )
...全文
144 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
心中的彩虹 2010-07-26
  • 打赏
  • 举报
回复
[Quote=引用楼主 hbgzg3006 的回复:]
SQL code

表A
id name agenum
表B
id age
--有没有好的办法把新的age数量赋值给表A的agenum,也就是id是同一个值的B表的数量变化后更新到A表的agenum
update A a set a.agenum=? where a.agenum!=(select count(*) from B b where a.id =b.id )


--merge into 10G的
merge into A t using B k on(t.id=k.id)
when matched then update set t.agenum=k.age


update A t set t.agenum=(select age from B k where t.id=k.id)
where exists(select 1 from B c where t.id=c.id)





[/Quote]
iqlife 2010-07-26
  • 打赏
  • 举报
回复
效率高的话,你要知道哪些做了变化,
可以先对B表进行统计,在获得A表达统计记录,对比,不同的再进行更新
--取出变化的,然后更新
SELECT id,CNT
FROM
A,(select ID,count(*) AS CNT from B GROUP BY ID) B
WHERE A.ID=B.ID AND A.agenum<>B.CNT



hbgzg3006 2010-07-26
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 minitoy 的回复:]

update A a set a.agenum=(select count(*) from B c where a.id =c.id )
where a.agenum!=(select count(*) from B b where a.id =b.id )
[/Quote]
呵呵。有没有效率高点的啊。用一个临时表
minitoy 2010-07-26
  • 打赏
  • 举报
回复
update A a set a.agenum=(select count(*) from B c where a.id =c.id )
where a.agenum!=(select count(*) from B b where a.id =b.id )
hbgzg3006 2010-07-26
  • 打赏
  • 举报
回复
其实。我还要更新name内容的,当agenum相等的时候就不更新了,不相等的时候就更新。
hbgzg3006 2010-07-26
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 phoenix_99 的回复:]

SQL code
update A a set a.agenum = (select age from B b where a.id = b.id)
where exists( select 1 from A,B where A.id=B.id)
[/Quote]
这个不相当于直接更新了么?
beita258 2010-07-26
  • 打赏
  • 举报
回复
表b insert触发器 可以试试
hbgzg3006 2010-07-26
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 java3344520 的回复:]

直接更新好了,即使相同也更新

update A a set a.agenum=(select count(*) from B b where a.id =b.id )
[/Quote]
没有好的办法么?更新数据多了会慢的吧。
minitoy 2010-07-26
  • 打赏
  • 举报
回复
update A a set a.agenum=(select count(*) from B b where a.id =b.id ) ;
Phoenix_99 2010-07-26
  • 打赏
  • 举报
回复
update A a set a.agenum = (select age from B b where a.id = b.id)
where exists( select 1 from A,B where A.id=B.id)
iqlife 2010-07-26
  • 打赏
  • 举报
回复
直接更新好了,即使相同也更新

update A a set a.agenum=(select count(*) from B b where a.id =b.id )
chooseforget 2010-07-26
  • 打赏
  • 举报
回复
触发器。在insert into B的时候将A表更新。

17,377

社区成员

发帖
与我相关
我的任务
社区描述
Oracle 基础和管理
社区管理员
  • 基础和管理社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧