如何从MySQL的DOB字段获取年龄?

要从MySQL的DOB字段获取年龄,可以使用以下语法。在这里,我们从当前日期减去DOB。

select yourColumnName1,yourColumnName2,........N,year(curdate())-
   year(yourDOBColumnName) as anyVariableName from yourTableName;

为了理解上述语法,让我们首先创建一个表。创建表的查询如下。

mysql> create table AgeDemo
-> (
-> StudentId int,
-> StudentName varchar(100),
-> StudentDOB date
-> );

使用insert命令在表中插入一些记录。查询如下。

mysql> insert into AgeDemo values(1,'John','1998-10-1');

mysql> insert into AgeDemo values(2,'Carol','1990-1-2');

mysql> insert into AgeDemo values(3,'Sam','2000-12-1');

mysql> insert into AgeDemo values(4,'Mike','2010-10-11');

使用select语句显示表中的所有记录。查询如下。

mysql> select *from AgeDemo;

以下是输出。

+-----------+-------------+------------+
| StudentId | StudentName | StudentDOB |
+-----------+-------------+------------+
| 1         | John        | 1998-10-01 |
| 2         | Carol       | 1990-01-02 |
| 3         | Sam         | 2000-12-01 |
| 4         | Mike        | 2010-10-11 |
+-----------+-------------+------------+
4 rows in set (0.00 sec)

这是从DOB计算年龄的查询。查询如下。

mysql> select StudentName,StudentDOB,year(curdate())-year(StudentDOB) as StudentAge from AgeDemo;

以下是显示年龄的输出。

+-------------+------------+------------+
| StudentName | StudentDOB | StudentAge |
+-------------+------------+------------+
| John        | 1998-10-01 | 21         |
| Carol       | 1990-01-02 | 29         |
| Sam         | 2000-12-01 | 19         |
| Mike        | 2010-10-11 | 9          |
+-------------+------------+------------+
4 rows in set (0.03 sec)