天天看點

SQL相關語句

其他函數 、 case 語句  

1. 聚合函數  

 max()  ,  min()  ,  avg() , sum() , count ()  

2. if(  bool表達式   ,  expr1   ,  expr2   )

 如果 bool表達式 成立 (true) , 就傳回  expr1 。 否則 如果 bool表達式 不成立 (false) , 就傳回  expr2 。

 類似于  java 語言中的 問号表達式 (  ? : )

   select sid,cid, if(mark>=60,'及格','不及格') as '成績'  from score

3. ifnull (   expr1   ,  expr2   )  

 如果 expr1  不為null  就傳回  expr1  自己。 否則 如果 expr1  為null , 就傳回  expr2 。  

   select * from score;

   update score set mark=null where sid=2001002 and cid='01'

   alter table score  

   modify mark decimal(8,2)  

   select ifnull(mark,0) from score

5. isnull  (  exp  )

 判斷  表達式(或者列名) exp 是否為null 。 如果 為null ,就傳回  1 (表示 : true)  , 否則傳回  0 (表示:false )

   select * from score where mark is null

   select * from score where isnull(mark)

6. case 語句

 (1) 文法1 :  類似于 java 語言中的 switch  

  case    表達式exp

   when   比較值1   then   '選擇的結果1'  

   when   比較值2   then   '選擇的結果2'  

   when   比較值3   then   '選擇的結果3'  

   when   比較值4   then   '選擇的結果4'  

   else   '選擇的結果5'  

  end

     select  

       case cid  

         when '01' then '國文'

         when '02' then '數學'

         else  '出錯'

       end  

    from score

 (2) 文法2 : 類似于 java 語言中的  if  

  case    

   when   bool表達式1   then   '選擇的結果1'  

   when   bool表達式2   then   '選擇的結果2'  

   when   bool表達式3   then   '選擇的結果3'  

   when   bool表達式4   then   '選擇的結果4'  

   else   '選擇的結果5'  

  end

  select sid,cid,

    case  

       when mark >=80 then '優秀'  

       when mark >=60 then '及格'