如何從 MySQL 中的出生日期欄位中獲取年齡?
要從 MySQL 中的 D.O.B 欄位中獲取年齡,可以使用以下語法。在這裡,我們從當前日期減去出生日期。
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)
使用插入命令在表中插入一些記錄。查詢如下。
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)
以下是計算 D.O.B 年齡的查詢。查詢如下。
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)
廣告