从MySQL中给定的出生日期计算年龄?
要从出生日期计算MySQL中的年龄,可以使用以下语法-
SELECT YEAR(CURRENT_TIMESTAMP) - YEAR(yourColumnName)- (RIGHT(CURRENT_TIMESTAMP, 5) < RIGHT(yourColumnName, 5)) as anyVariableName from yourTableName;
为了理解上述概念,让我们创建一个表。以下是创建表的查询。
mysql> create table AgeCalculatesDemo−> (
−> YourDateOfBirth datetime
−> );
借助insert命令将一些记录插入表中。这些记录是DOB,通过它们我们可以计算年龄。以下是查询-
mysql> insert into AgeCalculatesDemo values(date_add(now(),interval 22 year));mysql> truncate table AgeCalculatesDemo;
mysql> insert into AgeCalculatesDemo values(date_add(now(),interval -22 year));
mysql> insert into AgeCalculatesDemo values(date_add(now(),interval -12 year));
mysql> insert into AgeCalculatesDemo values(date_add(now(),interval -19 year));
mysql> insert into AgeCalculatesDemo values('2010-4-05');
现在,您可以在select语句的帮助下显示所有记录。以下是查询-
mysql> select *from AgeCalculatesDemo;
以下是输出-
+---------------------+| YourDateOfBirth |
+---------------------+
| 1996-12-06 23:35:26 |
| 2006-12-06 23:35:32 |
| 1999-12-06 23:35:42 |
| 2010-04-05 00:00:00 |
+---------------------+
4 rows in set (0.00 sec)
这是可用于计算年龄的查询。
mysql> SELECT YEAR(CURRENT_TIMESTAMP) - YEAR(YourDateOfBirth)−> - (RIGHT(CURRENT_TIMESTAMP, 5) < RIGHT(YourDateOfBirth, 5)) as YourAge
−> from AgeCalculatesDemo;
以下是显示年龄的输出-
+---------+| YourAge |
+---------+
| 22 |
| 12 |
| 19 |
| 8 |
+---------+
4 rows in set (0.00 sec)
以上是 从MySQL中给定的出生日期计算年龄? 的全部内容, 来源链接: utcz.com/z/345447.html