完结篇!MySQL经典50题-第46到50题

MySQL50-12-第46-50题

本文中介绍的是第46-50题,主要的知识点:各种时间和日期函数的使用

year() :返回年份 date_format(now(), '%Y%m%d') :返回年月日 dayofyear() :一年中的第几天 weekofyear() :一年中的第几周 week() :一年中的第几周 month() :返回月份 dayofweek() :星期索引,1代表星期1 weekday() :星期索引,0代表星期1

5个题目是:

  • 查询各学生的年龄:按照出生日期来算,当前月日 < 出生年月的月日则,年龄减1
  • 查询本周过生日的学生
  • 查询下周过生日的学生
  • 查询本月过生日的学生
  • 查询下月过生日的学生
  • 1、我们以出生年月日中的年份来计算年龄,通过 year() 来计算当前年份和出生年份的差值

    2、比较具体的日期和当前日期的大小,使用 dayofyear() 来确定每个出生日期是处在每年的哪一天;如果出生日期靠后,则说明最近这年还没有达到一岁,减去1

    3、 使用 case 语句来进行判断

    SQL实现

    自己的方法
    -- 自己的方法
    select *
        ,case when dayofyear(now()) >= dayofyear(s_birth) then year(now()) - year(s_birth) 
            when dayofyear(now()) < dayofyear(s_birth) then year(now()) - year(s_birth) - 1
        else 'other' end as 'age'
    from Student;
        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 0 else 1 end) as age  -- 当前日期大,说明已经过生了,年龄正常;反之说明今年还没有到年龄-1
    from Student;
    
    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
    

    查询下周过生日的学生

    本题和上面的题目是类似的,只是需要我们在现有的日期往前推一周

    SQL实现

    -- 自己的方法
    select *
    from Student
    where week(s_birth) = week(now()) + 1;   -- 往前推1周
    -- 参考方法
    select * from Student where week(date_format(now(),'%Y%m%d')) + 1= week(s_birth); 
    where mod(week(now()), 52) + 1 =  week(s_birth);
    

    当现在刚好是第52周,那么mod函数的结果是0,则说明出生的月份刚好是明年的第一周

    查询本月过生的同学

    我们通过month()来查询每个日期所在的月份