SQL语句之if,case

其他函数 、 case 语句

1. 聚合函数
max() , min() , avg() , sum() , count ()

2. if( bool表达式 , expr1 , expr2 )
如果 bool表达式 成立 (true) , 就返回 expr1 。 否则 如果 bool表达式 不成立 (false) , 就返回 expr2 。

类似于 java 语言中的 问号表达式 ( ? : )

select sid,cid, if(mark>=60,'及格','不及格') as '成绩' from score


3. ifnull ( expr1 , expr2 )
如果 expr1 不为null 就返回 expr1 自己。 否则 如果 expr1 为null , 就返回 expr2 。

select * from score;

update score set mark=null where sid=2001002 and cid='01'

alter table score
modify mark decimal(8,2)

select ifnull(mark,0) from score

5. isnull ( exp )
判断 表达式(或者列名) exp 是否为null 。 如果 为null ,就返回 1 (表示 : true) , 否则返回 0 (表示:false )

select * from score where mark is null

select * from score where isnull(mark)

6. case 语句
(1) 语法1 : 类似于 java 语言中的 switch

case 表达式exp
when 比较值1 then '选择的结果1'
when 比较值2 then '选择的结果2'
when 比较值3 then '选择的结果3'
when 比较值4 then '选择的结果4'
else '选择的结果5'
end

select

case cid
when '01' then '语文'
when '02' then '数学'
else '出错'
end

from score

(2) 语法2 : 类似于 java 语言中的 if

case
when bool表达式1 then '选择的结果1'
when bool表达式2 then '选择的结果2'
when bool表达式3 then '选择的结果3'
when bool表达式4 then '选择的结果4'
else '选择的结果5'
end

select sid,cid,
case
when mark >=80 then '优秀'
when mark >=60 then '及格'
else '不及格'
end as 'level'
from score

posted @   呆萌老师  阅读(288)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示