数据库系列之控制函数

1,085 阅读1分钟

这一节所用到的数据表结构如下:

image-20210920225311695.png

数据内容如下:

image-20210920225337749.png

1 if()函数

其用法如下:

if(condition, a, b):如果condition为真,返回a,否则返回b

1.1 基本用法

SELECT
    id,
    score,
IF
    ( score >= 60, "及格", "不及格" ) AS score_result 
FROM
    `chapter8`

result:

image-20210920225852790.png

1.2 if多层嵌套

SELECT
    id,
    score,
IF
    (
        score < 60,
        "不及格",
    IF
        ( score < 80, "良好", "优秀" )) AS score_result 
FROM
    `chapter8`

result:

image-20210920230226691.png

2 case when函数

2.1 对某一列进行多重判断

其形式如下:

case 列名
when 条件1 then 返回值1
when 条件2 then 返回值2
......
when 条件n then 返回值n
else 返回默认值
end

该种形式下的条件只能是具体的值,不能是比较运算

SELECT id, class,(CASE class
    WHEN "一班" THEN "class1"
    WHEN "二班" THEN "class2"
    WHEN "三班" THEN "class3"
    ELSE "其他"
END) class_result FROM chapter8

result:

image-20210921001741216.png

2.2 进行比较运算

其形式如下:

case
when 列名满足条件1 then 返回值1
when 列名满足条件2 then 返回值2
......
when 列名满足条件n then 返回值n
else 返回默认值
end

该种形式下的是支持列名比较运算

SELECT id, score,(CASE
    WHEN score < 60 THEN "不及格"
    WHEN score < 80 THEN "良好"
    ELSE "优秀"
END) score_result FROM chapter8

result:

image-20210921002256440.png