惊雷无声 发表于 2023-4-5 17:24:03

mysql精确查年龄

已知出生年月日,求到今天为止多少岁
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;
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: mysql精确查年龄