数据库更新就一种方法Update,
其标准格式:Update 表名 set 字段=值 where 条件
不过根据数据的来源不同,还是有所区别的:
1.从外部输入
这种比较简单
例:update tb set UserName="XXXXX" where UserID="aasdd"
2.一些内部变量,函数等,比如时间等
直接将函数赋值给字段
update tb set LastDate=date() where UserID="aasdd"
3.对某些字段变量+1,常见的如:点击率、下载次数等
这种直接将字段+1然后赋值给自身
update tb set clickcount=clickcount+1 where ID=xxx
4.将同一记录的一个字段赋值给另一个字段
update tb set Lastdate= regdate where XXX
5.将一个表中的一批记录更新到另外一个表中
table1
ID f1 f2
table2
ID f1 f2
先要将table2中的f1 f2 更新到table1(相同的ID)
update table1,table2 set table1.f1=table2.f1,table1.f2=table2.f2 where table1.ID=table2.ID
6.将同一个表中的一些记录更新到另外一些记录中
表:a
ID month E_ID Price
1 1 1 2
2 1 2 4
3 2 1 5
4 2 2 5
先要将表中2月份的产品price更新到1月份中
显然,要找到2月份中和1月份中ID相同的E_ID并更新price到1月份中
这个完全可以和上面的方法来处理,不过由于同一表,为了区分两个月份的,应该将表重命名一下
update a,a as b set a.price=b.price where a.E_ID=b.E_ID and a.month=1 and b.month=2
当然,这里也可以先将2月份的查询出来,在用5.的方法去更新
update a,(select * from a where month=2)as b set a.price=b.price where a.E_ID=b.E_ID and a.month=1
多表关联UPDATE
假设有两个表A和B,A表字段a,b,c,d,B表字段b,e,f,两表的关联条件是字段b,现在想做个data patch,欲将B表中的字段e的值patch给A表的字段c.
有如下两种方法:
update A set A.c=(select e from B where B.b=A.b) where exists(select 1 from B where B.b=A.b);
merge into A using B on (A.b=B.b) when matched then update set A.c=B.e;
上面两种方法都可以实现多表联结的更新,其中的B表也可以是子查询,视图。
merge into是oracle 9i之后添加的语法,可以实现update/insert的功能(满足条件更新,不满足条件插入),而且效率要高,因为用merge只需要一次全表扫描,但merge into的使用需要小心,必须理解它的用法才能放心使用,否则有可能出现问题。
上面的例子不仅仅可以更新单个字段,也可以更新多个字段,如下:
update A set A.c=(select e from B where B.b=A.b), A.d=(select f from B where B.b=A.b) where exists(select 1 from B where B.b=A.b); merge into A using B on (A.b=B.b) when matched then update set A.c=B.e, A.d=B.f;