手电筒 发表于 2023-4-5 15:44:20

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;
来源:https://www.cnblogs.com/dream-come-true/p/17287916.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: mysql精确查年龄