当前位置:   article > 正文

[Mysql] YEAR函数 | MONTH函数 | WEEK函数 | DAY函数_mysql 中的year_month是什么

mysql 中的year_month是什么

YEAR函数 | MONTH函数 | WEEK函数 | DAY函数用于提取日期片段

1.YEAR函数

YEAR函数用于返回date中的年份值

语法结构

YEAR(date)

  1. -- 2022
  2. SELECT YEAR('2022-05-23');
  3. SELECT YEAR('2022-05-23 15:30:00');

2.MONTH函数

MONTH函数用于返回date中的月份值

语法结构

MONTH(date)

  1. -- 5
  2. SELECT MONTH('2022-05-23');
  3. SELECT MONTH('2022-05-23 15:30:00');

3.WEEK函数

WEEK函数用于返回date中的星期数

语法结构

WEEK(date)

  1. -- 21
  2. SELECT WEEK('2022-05-23');
  3. SELECT WEEK('2022-05-23 15:30:00');

4.DAY函数

DAY函数用于返回date中的日期值

语法结构

DAY(date)

  1. -- 23
  2. SELECT DAY('2022-05-23');
  3. SELECT DAY('2022-05-23 15:30:00');

5.扩展练习案例 

数据导入

  1. DROP TABLE IF EXISTS Student;
  2. CREATE TABLE Student(
  3. SId varchar(10),
  4. Sname varchar(10),
  5. Sage datetime,
  6. Ssex varchar(10)
  7. )
  8. ENGINE = InnoDB
  9. DEFAULT CHARSET = utf8;
  10. insert into Student values('01' , '赵雷' , '1990-01-01' , '男');
  11. insert into Student values('02' , '钱电' , '1990-12-21' , '男');
  12. insert into Student values('03' , '孙风' , '1990-05-20' , '男');
  13. insert into Student values('04' , '李云' , '1990-08-06' , '男');
  14. insert into Student values('05' , '周梅' , '1991-12-01' , '女');
  15. insert into Student values('06' , '吴兰' , '1992-03-01' , '女');
  16. insert into Student values('07' , '郑竹' , '1989-07-01' , '女');
  17. insert into Student values('09' , '张三' , '2017-12-20' , '女');
  18. insert into Student values('10' , '李四' , '2017-12-25' , '女');
  19. insert into Student values('11' , '李四' , '2017-12-30' , '女');
  20. insert into Student values('12' , '赵六' , '2017-01-01' , '女');
  21. insert into Student values('13' , '孙七' , '2018-01-01' , '女');

student表

案例1:查询各学生的年龄,只按年份来算 

  1. SELECT *,(YEAR(NOW()) - YEAR(Sage)) AS age
  2. FROM student;

案例2:查询本周过生日的学生

  1. SELECT *
  2. FROM student
  3. WHERE WEEK(Sage) = WEEK(NOW());

案例3:查询下周过生日的学生 

  1. SELECT *
  2. FROM student
  3. WHERE WEEK(Sage) = WEEK(NOW())+1;

案例4:查询本月过生日的学生

  1. SELECT *
  2. FROM student
  3. WHERE MONTH(Sage) = MONTH(NOW());

案例5:查询下月过生日的学生

  1. SELECT *
  2. FROM student
  3. WHERE MONTH(Sage) = MONTH(NOW())+1;
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/361844
推荐阅读
相关标签
  

闽ICP备14008679号