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

วิธีแทรกวันที่และเวลาอัตโนมัติเมื่อ INSERT ค่าในคอลัมน์อื่นใน MySQL

ประกาศคอลัมน์ timestamp เป็น DEFAULT CURRENT_TIMESTAMP:

ตัวอย่าง

mysql> CREATE TABLE testing (
    -> StudentName VARCHAR(20) NOT NULL,
    -> RegDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    -> );
Query OK, 0 rows affected (0.49 sec)

mysql> INSERT INTO testing(StudentName) VALUES ('Ram');
Query OK, 1 row affected (0.14 sec)

mysql> INSERT INTO testing(StudentName) VALUES ('Shyam');
Query OK, 1 row affected (0.06 sec)

mysql> SELECT * FROM testing;
+-------------+---------------------+
| StudentName | RegDate             |
+-------------+---------------------+
| Ram         | 2017-10-28 21:24:24 |
| Shyam       | 2017-10-28 21:24:30 |
+-------------+---------------------+

ทุกครั้งที่ INSERT ค่าใน StudentName คอลัมน์ RegDate จะบันทึกวันที่-เวลาปัจจุบันอัตโนมัติ สะดวกสำหรับ audit trail