标签:
1. 科普下润年:
先安装mysql官方示例数据库employees。没安装的可以参考:《MAC安装MYSQL官方示例数据库EMPLOYEE》
-- 创建表employees create table employees like employees.employees; -- 将employees库的employees表数据插入到自己的表 insert into employees select * from employees.employees limit 0,10; -- 新增数据,生日为闰年1972-02-29 insert into employees select ‘10011‘,‘1972-02-29‘,‘Jiang‘,‘David‘,‘M‘,‘1990-2-20‘;
4. 查询用户和出生信息
-- 查询用户和出生信息 select concat(e.last_name, ‘ ‘, e.first_name) as Name, e.birth_date as BirthDate from employees e;
5. 实现
5.1 查询当前日期、当前日期和生日间隔的年数。
select concat(e.last_name, ‘ ‘, e.first_name) as Name, e.birth_date as BirthDay, (year(now())-year(e.birth_date)) diff, now() as today from employees e
5.2 查询当年的生日和下一年的生日。
select name,birthday,today, date_add(birthday, interval diff year) curr, -- 当年生日 date_add(birthday, interval diff+1 year) next -- 下一年生日 from ( select concat(e.last_name, ‘ ‘, e.first_name) as Name, e.birth_date as BirthDay, (year(now())-year(e.birth_date)) diff, now() as today from employees e ) as a
5.3 出生日期是29日,当年或下一年生日是28日,就将生日日期加1天
select name,birthday,today, date_add(curr, interval if(day(birthday)=29 && day(curr)=28, 1, 0) day) as cur, -- 闰年运行后的当年生日 date_add(next, interval if(day(birthday)=29 && day(next)=28, 1, 0) day) as next -- 闰年运行后的下一年生日 from ( select name,birthday,today, date_add(birthday, interval diff year) curr, -- 当年生日 date_add(birthday, interval diff+1 year) next -- 下一年生日 from ( select concat(e.last_name, ‘ ‘, e.first_name) as Name, e.birth_date as BirthDay, (year(now())-year(e.birth_date)) diff, now() as today from employees e ) as a ) as b
5.4 最终代码,如果当年生日已经过了就返回下一年生日。
select name,birthday, if(cur>today, cur, next) as birth_day -- 如果当年生日大于当前日期,生日为今年,否则为下一年 from( select name,birthday,today, date_add(curr, interval if(day(birthday)=29 && day(curr)=28, 1, 0) day) as cur, -- 闰年运行后的当年生日 date_add(next, interval if(day(birthday)=29 && day(next)=28, 1, 0) day) as next -- 闰年运行后的下一年生日 from ( select name,birthday,today, date_add(birthday, interval diff year) curr, -- 当年生日 date_add(birthday, interval diff+1 year) next -- 下一年生日 from ( select concat(e.last_name, ‘ ‘, e.first_name) as Name, e.birth_date as BirthDay, (year(now())-year(e.birth_date)) diff, now() as today from employees e ) as a ) as b ) as c
查询结果:
标签:
原文地址:http://www.cnblogs.com/frank-quan/p/5793246.html