mysql的if 和 case when


mysql中的條件語句主要有if 和case when。

首先,一個初始表格:felix_test

1. IF(expr1,expr2,expr3):如果第一個條件為True,則返回第二個參數,否則返回第三個

select if(author='Felix', 'yes', 'no') as AU from felix_test;

2. 用case when實現if

select case author when 'Felix' then 'yes' else 'no' end as AU from felix_test;  #用case when實現if

3. case when 多重判斷

select case author    #多重判斷
when 'Felix' then 'good'
when 'Tom' then 'top'
when 'Bob' then 'down'
else 'do not know' 
end
as AU 
from felix_test;

4. case when 多重判斷,另一種形式

select 
case when author='Felix' then 'good'
when author='Tom' then 'top'
when author='Bob' then 'down'
else 'do not know'
end 
as AU 
from felix_test;

5. ifnull 判斷是否為空:假如第一個參數為null,則返回第二個參數;否則直接返回第一個參數的值

select ifnull(author,'yes') from felix_test;

 

注:mysql里面的if和case when語句也是可以嵌套的。

#

參考:

https://www.cnblogs.com/dogeLife/p/11288169.html

https://blog.csdn.net/bingguang1993/article/details/83110557


免責聲明!

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



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