在 MySQL (InnoDb) 中计算年龄

2021-11-20 00:00:00 sql mysql

如果我将某人的出生日期以 dd-mm-yyyy 形式存储在表格中,然后从当前日期中减去它,那么返回的日期格式是什么?

If I have a persons date of birth stored in a table in the form dd-mm-yyyy and I subtract it from the current date, what format is the date returned in?

如何使用这种返回的格式来计算某人的年龄?

How can I use this returned format to calculate someone's age?

推荐答案

如果值存储为 DATETIME 数据类型:

If the value is stored as a DATETIME data type:

SELECT YEAR(CURRENT_TIMESTAMP) - YEAR(dob) - (RIGHT(CURRENT_TIMESTAMP, 5) < RIGHT(dob, 5)) as age 
  FROM YOUR_TABLE

考虑闰年时不太精确:

SELECT DATEDIFF(CURRENT_DATE, STR_TO_DATE(t.birthday, '%d-%m-%Y'))/365 AS ageInYears
  FROM YOUR_TABLE t 

相关文章