資料庫:twt001
資料表:aupkey
參考文章:sql中的case when用法
例,有如下更新條件
工資以上的職員,工資減少%
工資在到之間的職員,工資增加%
很容易考慮的是選擇執行兩次update語句,如下所示
--條件
update personnel
set salary = salary * 0.9
where salary >= 5000;
--條件
update personnel
set salary = salary * 1.15
where salary >= 2000 and salary < 4600;
但是事情沒有想象得那麼簡單,假設有個人工資塊。首先,按照條件,工資減少%,變成工資。接下來執行第二個sql時候,因為這個人的工資是在到的範圍之內,需增加%,最後這個人的工資結果是,不但沒有減少,反而增加了。如果要是反過來執行,那麼工資的人相反會變成減少工資。暫且不管這個規章是多麼荒誕,如果想要乙個sql 語句實現這個功能的話,我們需要用到case函式。**如下:
update personnel
set salary = case when salary >= 5000
then salary * 0.9
when salary >= 2000 and salary < 4600
then salary * 1.15
else salary end;
這裡要注意一點,最後一行的else salary是必需的,要是沒有這行,不符合這兩個條件的人的工資將會被寫成null,那可就大事不妙了。在case函式中else部分的預設值是null,這點是需要注意的地方。
這種方法還可以在很多地方使用,比如說變更主鍵這種累活。
一般情況下,要想把兩條資料的primary key,a和b交換,需要經過臨時儲存,拷貝,讀回資料的三個過程,要是使用case函式的話,一切都變得簡單多了。
表內容及欄位設定如下:
假設有如上資料,需要把主鍵a和b相互交換。用case函式來實現的話,**如下 :
update aupkey
set p_key = case when p_key = 'a'
then 'b'
when p_key = 'b'
then 'a'
else p_key end
where p_key in ('a', 'b');
檢視表內容: 發現主鍵a,b已經交換
再執行一次程式,表將還原為原來的狀態
UPDATE 時主鍵衝突引發的思考
假設有乙個表,結構如下 mysql create table a id int 10 unsigned not null auto increment,id2 int 10 unsigned not null default 0 primary key id engine myisam 該表中只有6...
UPDATE 時主鍵衝突引發的思考
假設有乙個表,結構如下 mysql create table a id int 10 unsigned not null auto increment,id2 int 10 unsigned not null default 0 primary key id engine myisam 該表中只有6...
update多列的幾種選擇
當 update 多列 時有如下幾種選擇 1.教科書式寫法 update t table a set f1 select f1 from testz b where a.id b.id f2 select f2 from testz b where a.id b.id f3 select f3 fr...