在MySQL中计算出生日期起的年龄?
要从出生日期开始计算年龄,您可以使用以下语法-
select timestampdiff(YEAR,yourColumnName,now()) AS anyAliasName from yourTableName;
让我们首先创建一个表-
mysql> create table DemoTable ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentDOB datetime );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(StudentDOB) values('1996-01-12'); mysql> insert into DemoTable(StudentDOB) values('1990-12-31'); mysql> insert into DemoTable(StudentDOB) values('1989-04-01'); mysql> insert into DemoTable(StudentDOB) values('2000-06-17');
以下是使用select语句显示表中所有记录的查询-
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)