原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://yukai.blog.51cto.com/1761494/372585
今天遇到数据库的一个更新操作.
1个数据库中有两个表(其中一个表是从另一个数据库复制来的,方法见我以前文章),这两个表通过公司名称对应起来,其中一个有称谓(Mr.,Miss.,Mrs),另一个没有,将这个表的称谓导入到另一个表中:
sql: update tb_company set tb_company.Salutation1=tb_companyorg.Title from tb_company,tb_companyorg where tb_company.CompanyName_eng=tb_companyorg.Company_name
此sql语句作用为:将tb_companyorg表的Title(称谓)导入到tb_company表的Salutation1(称谓)字段中,通过两表的公司名称进行对应,一次性导入了17w+条数据
参考link:http://www.cnblogs.com/ywkpl/archive/2008/03/11/1101276.html
参考内容:
Product(pid,name,amount,nowAmount):标识,名称,已有数量,当前数量
Trade(id,pid,operType,number):标识,产品标识,操作类型(入库:1,出库:0),数量
Product表中测试数据:
1 | 苹果 | 100 | 0 |
2 | 桔子 | 50 | 0 |
Trade表中测试数据:
1 | 1 | 1 | 432 |
2 | 1 | 0 | 50 |
3 | 2 | 1 | 20 |
4 | 2 | 0 | 40 |
5 | 1 | 1 | 30 |
6 | 2 | 0 | 20 |
现要求一条SQL语句更新Product表中nowMount值
语句如下:
update p set p.nowAmount = p.amount+t.number
from Product as p ,(select pid,sum(case operType when ‘0‘ then number* (-1) else number end) number
from Trade group by pid) as t where t.pid=s.pid
from Product as p ,(select pid,sum(case operType when ‘0‘ then number* (-1) else number end) number
from Trade group by pid) as t where t.pid=s.pid
或者
update p
set p.nowAmount= t.number+p.amount
from Product as p
inner join (select pid ,sum(case operType when ‘0‘ then number* (-1) else number end) as number from Trade group by pid) as t
on p.pid=t.pid
set p.nowAmount= t.number+p.amount
from Product as p
inner join (select pid ,sum(case operType when ‘0‘ then number* (-1) else number end) as number from Trade group by pid) as t
on p.pid=t.pid
两者一样执行后Product表:
1 | 苹果 | 100 | 512 |
2 | 桔子 | 50 | 10 |