首頁  >  文章  >  資料庫  >  MYSQL控制流程函數CASE是如何運作的?

MYSQL控制流程函數CASE是如何運作的?

王林
王林轉載
2023-09-06 17:17:021063瀏覽

MYSQL控制流程函數CASE是如何運作的?

MySQL CASE 語句是一種流程控制功能,讓我們可以在查詢中建立條件,例如 SELECT 或 WHERE 子句。我們有兩種CASE 語句語法

Syntax-1

CASE val
WHEN compare_val1 THEN result1
WHEN compare_val2 THEN result2
.
.
.
Else result
END

在第一個語法中,如果val 等於compare_val1,則CASE 語句傳回result1。如果 val 等於 compare_val2,則 CASE 語句傳回 result2,依此類推。

如果 val 與任何compare_val 都不匹配,則CASE 語句會傳回 ELSE 子句中指定的結果

範例

mysql> Select CASE 100
    -> WHEN 100 THEN 'It is matched'
    -> WHEN 200 THEN 'It is not matched'
    -> ELSE 'No use of this Number'
    -> END as 'Matching the Number';
+---------------------+
| Matching the Number |
+---------------------+
| It is matched       |
+---------------------+
1 row in set (0.06 sec)

語法2

CASE
WHEN condition_1 THEN result1
WHEN condition_2 THEN result2
.
.
.
Else result
END

在第二種語法中,CASE 語句傳回結果 1、結果 2 等。如果條件為真。如果所有條件均不成立,CASE 語句將傳回 ELSE 子句中指定的結果

範例

mysql> Select CASE
    -> WHEN (100 = 100) THEN 'It is Matched'
    -> WHEN (200 = 100) Then 'It is Not Matched'
    -> Else 'No use of Number'
    -> END as 'Matching the Number';
+---------------------+
| Matching the Number |
+---------------------+
| It is Matched       |
+---------------------+
1 row in set (0.00 sec)
#

以上是MYSQL控制流程函數CASE是如何運作的?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除