更新(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=2as b set a.price=b.price where a.E_ID=b.E_ID and a.month=1

猜你喜欢

转载自blog.csdn.net/awiner/article/details/78461909