如何在 MySQL 中从出生日期获取年龄?
mysqlmysqli database
要从出生日期获取年龄,您可以使用 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 -> ); Query OK, 0 rows affected (0.73 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable(DateOfBirth) values('1998-06-04 12:30:00'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable(DateOfBirth) values('2000-01-31 04:10:20'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable(DateOfBirth) values('2010-12-01 03:50:45'); Query OK, 1 row affected (0.24 sec)
使用 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)