IF函数(类似于三元表达式的效果):
IF(expr,expr_true,expr_false)
当expr为true时,if函数返回expr_true的值;否则返回expr_false的值
eg:
SELECT
*,
IF
( stu_sex='男', "1", "0" ) AS sex
FROM
stu
在结果集中,stu_sex为男的sex都为1,其余情况为0
IFNULL(expr1,expr2)
当expr1的值不为null时,函数返回expr1;否则返回expr2
SELECT IFNULL(null,"is null") -->is null
SELECT IFNULL("not null","expr2") -->not null
case:用于判断分支
语法:
Case […]
When … then … [When … then …]
[else …]
end
eg:
- 在成绩表中按不通过分数段统计人数
统计课程1下,不同分数段的学生人数:
SELECT
count(case when score<30 then 1 end) as '<30',#then 1 表示该行返回1,则count计数器加1
count(case when score>29 and score<50 then 1 end) as '29<score<50',
count(case when score>49 then 1 end ) as '50<'
FROM
scores
WHERE course_id=1
- case在行中对数据的处理用例
SELECT *
,case
when score<30 then '<30'
when score>29 and score<50 then "<50"
else '>49'
end as score_area #显示每行不同分值的人所属的分段
,case course_id
when 1 then '1_name'
when 2 then '2_name'
else '?_name'
end as course_name #更具课程id转换每行的课程名
FROM scores