一、单条件判断if
在sql中,条件判断函数if用于根据指定的条件返回不同的值。
语法:
if(condition, value_if_true, value_if_false)
参数说明:
- condition:要判断的条件。
- value_if_true:如果条件为真,则返回的值。
- value_if_false:如果条件为假,则返回的值。
示例:
假设有如下名为studensts的表,包含id、name和score字段:
create table `students` ( `id` int(11) not null, `name` varchar(255) collate utf8mb4_bin default null, `score` int(11) default null, primary key (`id`) ) engine=innodb default charset=utf8mb4 collate=utf8mb4_bin;
我们想根据学生的分数判断是否及格,并返回相应的结果。
select id, name, if(score >= 60, '及格', '不及格') as result from students;
以上查询会返回一个结果集,其中result列将显示每个学生的及格或不及格的结果。
二、多条件判断case when
在sql中,条件判断函数case when用于在查询中根据特定条件返回不同的结果。
语法:
case when condition1 then result1 when condition2 then result2 ... else resultn end
参数说明:
- condition1、condition2等是条件表达式。
- result1、result2等是根据条件表达式返回的结果
- else子句是可选的,用于指定当所有条件都不满足时返回的默认结果。
示例:
例如,下面的示例查询根据学生成绩的不同等级返回不同的提示信息:
select name, case when score >= 90 then '优秀' when score >= 80 then '良好' when score >= 70 then '中等' when score >= 60 then '及格' else '不及格' end as grade from students;
以上查询会根据学生的成绩等级返回相应的提示信息,并将结果命名为grade列。
到此这篇关于sql中的单条件判断函数if和多条件判断case when的用法的文章就介绍到这了,更多相关sql 单条件判断函数和多条件判断内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论