要在MySQL查询中使用BirthDate列获取Age,可以使用datediff()
。让我们首先创建一个表:
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, DateOfBirth date );
以下是使用insert命令在表中插入一些记录的查询:
mysql> insert into DemoTable(DateOfBirth) values('2010-01-21'); mysql> insert into DemoTable(DateOfBirth) values('1993-04-02'); mysql> insert into DemoTable(DateOfBirth) values('1999-12-01'); mysql> insert into DemoTable(DateOfBirth) values('1998-11-16'); mysql> insert into DemoTable(DateOfBirth) values('2004-03-19');
以下是使用select命令显示表中记录的查询:
mysql> select *from DemoTable;
这将产生以下输出:
+----+-------------+ | Id | DateOfBirth | +----+-------------+ | 1 | 2010-01-21 | | 2 | 1993-04-02 | | 3 | 1999-12-01 | | 4 | 1998-11-16 | | 5 | 2004-03-19 | +----+-------------+ 5 rows in set (0.00 sec)
现在让我们使用使用DATEDIFF()
方法的生日日期列获取年龄:
mysql> select cast(DATEDIFF(curdate(),DateOfBirth) / 365.25 AS UNSIGNED) AS AGE from DemoTable;
这将产生以下输出:
+------+ | AGE | +------+ | 9 | | 26 | | 19 | | 20 | | 15 | +------+ 5 rows in set (0.00 sec)
现在让我们编写一个查询来获取年龄在20到26之间的DOB和ID:
mysql> SELECT *FROM DemoTable WHERE YEAR(CURDATE())-YEAR(DateOfBirth) BETWEEN 20 AND 26;
这将产生以下输出:
+----+-------------+ | Id | DateOfBirth | +----+-------------+ | 2 | 1993-04-02 | | 3 | 1999-12-01 | | 4 | 1998-11-16 | +----+-------------+ 3 rows in set (0.00 sec)