MySQL 基本查询46--50
Bitgeek 2022-07-15 MySQL
# 题目46:查询各学生的年龄:按照出生日期来算,当前月日 < 出生年月的月日则,年龄减1
select
s_name
,s_birth
,date_format(now(), '%Y') - date_format(s_birth, '%Y') - (case when date_format(now(), '%m%d') < date_format(s_birth, '%m%d') then 1 else 0 end) as age -- 当前日期大,说明已经过生了,年龄正常;反之说明今年还没有到年龄-1
from Student;
# 题目47:查询本周过生日的学生
select * from Student where week(date_format(now(),'%Y%m%d')) = week(s_birth); -- 方式1
select * from student where yearweek(s_birth) = yearweek(date_format(now(),'%Y%m%d')); -- 方式2
# 题目48:查询下周过生日的学生
select * from Student where week(date_format(now(),'%Y%m%d')) + 1= week(s_birth);
边界问题 如果现在刚好的是今年的最后一个周,那么下周就是明年的第一个周,我们如何解决这个问题呢??改进后的脚本:
select * from Student
where mod(week(now()), 52) + 1 = week(s_birth);
当现在刚好是第52周,那么mod函数的结果是0,则说明出生的月份刚好是明年的第一周
# 题目49:查询本月过生日的同学
select * from Student where month(date_format(now(), '%Y%m%d')) = month(s_birth);
# 题目50:查询下月过生日的同学
select * from Student
where month(date_format(now(), '%Y%m%d')) + 1= month(s_birth);
边界问题 假设现在是12月份,那么下个月就是明年的1月份,我们如何解决???将上面的代码进行改进:
select * from Student
where mod(month(now()),12) + 1 = month(s_birth);
如果现在是12月份,则mod函数的结果是0,说明生日刚好是1月份