1. 程式人生 > >MySQL 如何利用一條語句實現類似於if-else條件語句的判斷

MySQL 如何利用一條語句實現類似於if-else條件語句的判斷

一、 編寫一條update句實現商品具體規則如下

199,提價20%

2100-999之間,提價10%

31000-1999間,提價5%

4其他提價2%

update goods
set price = (
case 
  when price between 0 and 99 then price * 1.2
  when price between 100 and 999 then price * 1.1
  when price between 1000 and 1999 then price * 1.05
  when price > 1999 then price * 1.02
end);
select * from goods;

二、 編寫一條select句,實現如下效果

   姓名

-------------------------------------------------

 1        張三  86   良好

 2       李四   98   優秀

 3       王五   72   及格

 4       那六   69   及格

 5       小么   56   不及格

規則如下:

1>=90優秀

2>=80良好

3>=60及格

4<60不及格

select id as 學號, name as 姓名, score as 分數, 
@<span style="font-family:宋體;">level</span>:=(
  case 
    when score >= 90 then '優秀'
    when score >= 80 and score < 90 then '良好'
    when score >= 60 and score < 80 then '及格'
    when score < 60 then '不及格'
  end
)
as 等級
from scores;