如何在MySQL中从DOB获得年龄?
要从DOB获取年龄,可以使用该TIMESTAMPDIFF()
方法。以下是语法-
select TIMESTAMPDIFF(YEAR, yourColumnName, CURRENT_DATE) AS anyAliasName from yourTableName;
让我们首先创建一个表-
mysql> create table DemoTable -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> DateOfBirth datetime -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(DateOfBirth) values('1998-06-04 12:30:00'); mysql> insert into DemoTable(DateOfBirth) values('2000-01-31 04:10:20'); mysql> insert into DemoTable(DateOfBirth) values('2010-12-01 03:50:45');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
输出结果
+----+---------------------+ | Id | DateOfBirth | +----+---------------------+ | 1 | 1998-06-04 12:30:00 | | 2 | 2000-01-31 04:10:20 | | 3 | 2010-12-01 03:50:45 | +----+---------------------+ 3 rows in set (0.00 sec)
以下是从MySQL中的DOB获取年龄的查询-
mysql> select TIMESTAMPDIFF(YEAR, DateOfBirth, CURRENT_DATE) AS YourAge from DemoTable;
输出结果
+---------+ | YourAge | +---------+ | 21 | | 19 | | 8 | +---------+ 3 rows in set (0.00 sec)