sql中的if()和ifnull() 的用法和區別


if()

把salary表中的女改成男,男改成女:

update salary set sex = if( sex = '男','女','男');

 

if(true,a,b),  if(false,a,b) 這個就是第一個如果是true,就等於a,false就等於b,有點像三元表達式

 

 

ifnull(null, a),ifnull(a,b),    ifnull里有兩個數,如果第一個不是null,是a非null,就都等於a, 如果a=Null,就都為a。

 

eg:

 

SELECT IFNULL(NULL,"11"); -> 11

SELECT IFNULL("00","11"); -> 00

 

 

 

與if()和ifnull()作用相同的,還有一個,就是case when  then else end

舉例:

1case sex when 1 then '男' when 2 then '女' else '其他' end 

這個就是把表中的sex字段1,換成男,2換成女,都不是換成其他,也可以寫作:

2case when sex = 1 then '男' when sex = 2 then ‘女’ else '其他' end 

 

1叫做簡單case函數   2叫做case搜索函數,功能相同,但是case搜索函可以寫條件判定,比如不等於,而簡單case函數只能是=

還有一點要注意的是:case函數如果滿足第一個條件,就會忽略第二個條件

case when id in (1,2) then '第一類' when id in (1) then '第二類' esle '其他' end

你永遠不會得到第二類這個結果

select name,id ,sex,(case sex when 1 then '男' when 2 then '女' esle '其他' end ) 性別 from users

 

 

 

重點: case和sum結合還可以實現分段統計

select sum(case sex when 1 then 1 else 0 end) 男性,sum(case sex when 2 then 1 else 0 end) 女性,sum(case  when sex <> 1 and sex <> 2 then 1 else 0 end)其他 from users

 

文章開頭的那題:

select (case sex when '男' then '女' when '女' then '男' end ) from salary;

update salary set sex = case sex when 'f' then 'm' else 'f' end ;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM