如何从 MySQL 中的出生日期字段获取年龄?

mysqlmysqli database

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

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

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

mysql> create table AgeDemo
-> (
-> StudentId int,
-> StudentName varchar(100),
-> StudentDOB date
-> );
Query OK, 0 rows affected (0.61 sec)

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

mysql> insert into AgeDemo values(1,'John','1998-10-1');
Query OK, 1 row affected (0.20 sec)

mysql> insert into AgeDemo values(2,'Carol','1990-1-2');
Query OK, 1 row affected (0.14 sec)

mysql> insert into AgeDemo values(3,'Sam','2000-12-1');
Query OK, 1 row affected (0.15 sec)

mysql> insert into AgeDemo values(4,'Mike','2010-10-11');
Query OK, 1 row affected (0.18 sec)

使用 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)

以下是根据出生日期计算年龄的查询。查询如下。

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)

相关文章