借助MySQL中的DATE_FORMAT()方法,根据出生日期计算年龄。首先,借助now()
method获取当前日期时间,然后可以将出生日期放在DATE_FORMAT()中。
语法如下-
SELECT DATE_FORMAT(FROM_DAYS(DATEDIFF(now(),'yourDateofbirth')), '%Y')+0 AS anyVariableName;
应用以上语法从yourdateofbirth计算年龄。在上述语法中,将yourDateofbirth替换为您的出生日期。查询如下-
SELECT DATE_FORMAT(FROM_DAYS(DATEDIFF(now(),'2010-11-25')), '%Y')+0 AS Age;
以下是输出-
+------+ | Age | +------+ | 8 | +------+ 1 row in set (0.00 sec)
现在让我们看一个例子。首先,创建一个表-
mysql> create table AgeCalculationFromDatetime -> ( -> YourDateofBirth datetime -> );
将出生日期插入表格。查询如下-
mysql> insert into AgeCalculationFromDatetime values('1995-11-25');
在select语句的帮助下显示所有记录。查询如下-
mysql> select *from AgeCalculationFromDatetime;
以下是输出-
+---------------------+ | YourDateofBirth | +---------------------+ | 1995-11-25 00:00:00 | +---------------------+ 1 row in set (0.00 sec)
计算年龄的查询如下-
mysql> SELECT DATE_FORMAT(FROM_DAYS(DATEDIFF(now(),YourDateofBirth)), '%Y')+0 AS Age from AgeCalculationFromDatetime;
这是输出-
+------+ | Age | +------+ | 23 | +------+ 1 row in set (0.00 sec)`