1. 程式人生 > >幾種更新(Update語句)查詢的方法

幾種更新(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