几种更新(Update语句)查询的方法

正 文:

数据库更新就一种方法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

原文地址:https://www.cnblogs.com/zfyouxi/p/3870433.html