如何从出生日期计算 MySQL 中的年龄?
要从出生日期计算年龄,你可以使用以下语法 -
select timestampdiff(YEAR,yourColumnName,now()) AS anyAliasName from yourTableName;
让我们先创建一个表 -
mysql> create table DemoTable ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentDOB datetime ); Query OK, 0 rows affected (0.61 sec)
使用插入命令在表中插入一些记录 -
mysql> insert into DemoTable(StudentDOB) values('1996-01-12'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(StudentDOB) values('1990-12-31'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(StudentDOB) values('1989-04-01'); Query OK, 1 row affected (0.45 sec) mysql> insert into DemoTable(StudentDOB) values('2000-06-17'); Query OK, 1 row affected (0.16 sec)
以下是使用选择语句从表中显示所有记录的查询 -
mysql> select *from DemoTable;
这将产生以下输出 -
+-----------+---------------------+ | StudentId | StudentDOB | +-----------+---------------------+ | 1 | 1996-01-12 00:00:00 | | 2 | 1990-12-31 00:00:00 | | 3 | 1989-04-01 00:00:00 | | 4 | 2000-06-17 00:00:00 | +-----------+---------------------+ 4 rows in set (0.00 sec)
以下是用于从出生日期计算年龄的查询 -
mysql> select timestampdiff(YEAR,StudentDOB,now()) AS AGE from DemoTable;
这将产生以下输出 -
+------+ | AGE | +------+ | 23 | | 28 | | 30 | | 18 | +------+ 4 rows in set (0.03 sec)
广告