表信息
准备知识
select now(); #当前日期时间
select curdate (); #当前日期
select curtime(); #当前时间
weekday(date) #返回日期的星期索引(0=周一,1=周二,,,6=周日)
subdate(date,间隔天数) #从指定日前减去几天 注意:当第二个参数为负数时,减去负数相当于加,这时表示从指定日期加上几天。
date_format(日期时间,格式) 详细日期格式设置见 MySQL DATE_FORMAT() 函数
当前日期时间:
1 -- 查询各学生的年龄
select s_name, year(curdate())-year(s_age) as 年龄 from student group by s_name;
2 -- 查询本周过生日的学生 between... and
select s_name from student
where date_format(s_age, '%m-%d')
between date_format(subdate(curdate(),weekday(curdate())),'%m-%d') and date_format(subdate(curdate(),weekday(curdate())-6),'%m-%d');
3 -- 查询下周过生日的学生
select s_name from student
where date_format(s_age, '%m-%d')
between date_format(subdate(curdate(),weekday(curdate())-7),'%m-%d') and date_format(subdate(curdate(),weekday(curdate())-13),'%m-%d');
4 -- 查询本月过生日的学生
select s_name from student where month(s_age) = month(curdate());
5 --查询下月过生日的学生
select s_name from student where month(s_age) =case when month(curdate()) + 1>12 then 1 else month(curdate()) + 1 end;
#注意:判断当月份为12月的时候,下月为1月。
# 总结一下case when 的用法:
case when (条件) then (结果1) else (结果2) end;
相比较excel的if()函数:
=if (条件,结果1,结果2)