Get difference in years between two dates in MySQL as an integer

后端 未结 9 2047
死守一世寂寞
死守一世寂寞 2020-11-30 10:59

I am trying to calculate how old is a person in a database.
Let\'s suppose to have this simple table:

student(id, birth_date);

Where

9条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 11:22

    I have not enough reputation to add comment to an answer by Rat-a-tat-a-tat Ratatouille to improve his code. Here is the better SQL-query:

    SELECT IFNULL(TIMESTAMPDIFF(YEAR, birthdate, CURDATE()), YEAR(CURDATE()) - YEAR(birthdate)) AS age
    

    This is better because sometimes "birthdate" may contain only year of birth, while day and month is 0. If TIMESTAMPDIFF() returns NULL, we can find rough age by subtracting the current year from the year of birth.

提交回复
热议问题