Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

วิธีคำนวณอายุจากฟิลด์ Date of Birth ใน MySQL

การคำนวณอายุจากวันที่เกิด

ใช้ฟังก์ชัน YEAR() และ CURDATE() คำนวณความต่างของปี

รูปแบบคำสั่ง

SELECT yourColumnName1, yourColumnName2, ..., 
       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');
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');

ข้อมูลทั้งหมด

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)

ข้อควรระวัง: วิธีนี้คำนวณจากปีเท่านั้น อาจไม่แม่นยำหากวันเกิดยังไม่ถึงในปีปัจจุบัน สำหรับการคำนวณที่แม่นยำขึ้น ควรใช้ TIMESTAMPDIFF(YEAR, dob, CURDATE())

วิธีที่แม่นยำกว่า

SELECT TIMESTAMPDIFF(YEAR, StudentDOB, CURDATE()) AS AccurateAge
FROM AgeDemo;