MySQL中case when 語句條件查詢的方法

來源:互聯網
上載者:User

case
計算條件列表並返回多個可能結果運算式之一。

case 具有兩種格式:

簡單 case 函數將某個運算式與一組簡單運算式進行比較以確定結果。


case 搜尋Function Compute一組布林運算式以確定結果。
兩種格式都支援可選的 else 參數。

文法
簡單 case 函數:

case input_expression
    when when_expression then result_expression
        [ ...n ]
    [
        else else_result_expression
    end

case 搜尋函數:

case
    when boolean_expression then result_expression
        [ ...n ]
    [
        else else_result_expression
    end


例如,下面的語句顯示中文年月
select getdate() as 日期,case month(getdate())
when 11 then '十一'
when 12 then '十二'
else substring('一二三四五六七八九十', month(getdate()),1)
end+'月' as 月份

下面看個執行個體


資料表為demotable,欄位有id, condition1,condition2,condition3,condition4,condition5

要求是查詢demotable中,condition1,condition2,condition3,condition4,condition5五個欄位中符合任意兩個或兩個以上的條件的內容。

可使用case when來實現這個條件,需要嵌套子查詢語句

sql語句程式碼範例如下:
複製代碼 代碼如下:
select * from demotable
where ((select case 1 when condition1滿足條件 then 1 else 0 end from demotable )
+(select case 1 when condition2滿足條件 then 1 else 0 end from demotable)
+(select case 1 when condition3滿足條件 then 1 else 0 end from demotable)
+(select case 1 when condition4滿足條件 then 1 else 0 end from demotable)
+(select case 1 when condition5滿足條件 then 1 else 0 end from demotable))>=2


case運算式的預設傳回值類型是任何傳回值的相容集合類型,但具體情況視其所在語境而定。如果用在字串語境中,則返回結果味字串。如果用在數字語境中,則返回結果為十進位值、實值或整數值。

if(expr1,expr2,expr3)

如果 expr1 是true (expr1 <> 0 and expr1 <> null),則 if()的傳回值為expr2; 否則傳回值則為 expr3。if() 的傳回值為數字值或字串值,具體情況視其所在語境而定。

mysql教程> select if(1>2,2,3);

-> 3

mysql> select if(1<2,'yes ','no');

-> 'yes'

mysql> select if(strcmp('test','test1'),'no','yes');

-> 'no'


意,為了在 group by 塊中使用 case,查詢語句需要在 group by 塊中重複 select 塊中的 case 塊。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.