已知出生年月日,求到今天为止多少岁
select *,
--如果当前月份大于出生月,年龄 = 当前年份 - 出生年
if (month(current_date())-month(substr(id_card,7,8))>0,
year(current_date())-year(substr(id_card,7,8)),
--如果当前月份小于出生月,年龄 = 当前年份 - 出生年 - 1
if(
month(current_date())-month(substr(id_card,7,8))<0,
year(current_date())-year(substr(id_card,7,8))-1,
--如果当前月份等于出生月,比较日期
if(
--当前日期大于出生日期 ,年龄 = 当前年份 - 出生年
day(current_date())-day(substr(id_card,7,8))>0,
year(current_date())-year(substr(id_card,7,8)),
---当前日期小于出生日期 ,年龄 = 当前年份 - 出生年 - 1
year(current_date())-year(substr(id_card,7,8))-1
)
)
)as 'age'
from person limit 10;
标签:current,substr,精确,year,date,年龄,id,card
From: https://www.cnblogs.com/dream-come-true/p/17287916.html