SQL相关语句

时间:2022-11-05 07:12:19

其他函数 、 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 '及格'

       else '不及格'  

    end  as 'level'

  from score