# md函數筆記五 註:筆記旨在記錄 五、MySQL 流程式控制制函數 | \ | 函 數 名 稱 | 作 用 | 完 成 | |: :|: |: |: :| | 1 | IF | 條件判斷 | 勾 | | 2 | IFNULL | 判空判斷 | 勾 | | 3 | CASE | 求數量 | 勾 | 0 ...
# md函數筆記五
目錄註:筆記旨在記錄
五、MySQL 流程式控制制函數
\ | 函 數 名 稱 | 作 用 | 完 成 |
---|---|---|---|
1 | IF |
條件判斷 | 勾 |
2 | IFNULL |
判空判斷 | 勾 |
3 | CASE |
求數量 | 勾 |
0.表
0.1 num表:
CREATE TABLE `anyot`.`Untitled` (
`id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`rand_int_num` int NULL DEFAULT NULL,
`rand_decimal_num` decimal(65, 2) NULL DEFAULT NULL,
`rand_string_num` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
1. IF() -- 條件判斷
1.1. 函數:
IF(expr1,expr2,expr3)
: expr1為判斷條件,符合則返回expr2,否則expr3
1.2. sql示例:
SELECT rand_int_num,IF(rand_int_num < 15,"√","×") from num
2. IFNULL() -- 判空判斷
2.1. 函數:
IFNULL(expr1,expr2)
:expr1為判斷的值或欄位,為空則返回expr2
2.2. sql示例:
SELECT rand_int_num,IFNULL(rand_int_num,"√") from num
3. CASE -- 求總數
3.1. 函數:
註: case結合when,else,end使用;其中else可以省略,但end一定要加。
-
寫法一:
CASE case_value WHEN when_value THEN statement_list WHEN ... ELSE statement_list END;
-
寫法二:
CASE WHEN expr1 THEN statement_list WHEN ... ELSE statement_list END;
3.2. sql示例:
-
寫法一:
SELECT rand_int_num, CASE rand_int_num WHEN 14 THEN " == 14" WHEN 44 THEN " == 44" ELSE " != 14" END as is14 from num
-
寫法二:
SELECT rand_int_num, CASE WHEN rand_int_num = 14 THEN " == 14" ELSE " != 14" END as is14 ,rand_string_num, CASE WHEN rand_string_num = "a99" THEN " == a99" ELSE " != a99" END as isa99 from num
SELECT CASE
WHEN WEEKDAY(NOW())=0 THEN '星期一'
WHEN WEEKDAY(NOW())=1 THEN '星期二'
WHEN WEEKDAY(NOW())=2 THEN '星期三'
WHEN WEEKDAY(NOW())=3 THEN '星期四'
WHEN WEEKDAY(NOW())=4 THEN '星期五'
WHEN WEEKDAY(NOW())=5 THEN '星期六'
WHEN WEEKDAY(NOW())=6 THEN '星期天'
END AS COLUMN1,NOW(),WEEKDAY(NOW()),DAYNAME(NOW());