เพื่ออัปเดตวันที่และเวลาปัจจุบันเพิ่ม 5 วัน คุณต้องใช้ NOW() + INTERVAL 5 DAY ซึ่งจะอัปเดตวันที่-เวลาทั้งหมด คือ วัน ชั่วโมง นาที และวินาที มาสร้างตารางเพื่อทำความเข้าใจ:
mysql> create table UserInformationExpire ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, UserName varchar(10), UserInformationExpireDateTime datetime not null ); Query OK, 0 rows affected (0.83 sec)
แทรกข้อมูลลงในตาราง:
mysql> insert into UserInformationExpire(UserName,UserInformationExpireDateTime) values('Maxwell','2019-02-09 23:56:27'); Query OK, 1 row affected (0.22 sec) mysql> insert into UserInformationExpire(UserName,UserInformationExpireDateTime) values('Carol','2018-11-21 15:45:21'); Query OK, 1 row affected (0.24 sec) mysql> insert into UserInformationExpire(UserName,UserInformationExpireDateTime) values('Bob','2019-01-22 16:30:35'); Query OK, 1 row affected (0.25 sec) mysql> insert into UserInformationExpire(UserName,UserInformationExpireDateTime) values('Larry','2017-12-25 17:20:33'); Query OK, 1 row affected (0.20 sec)แสดงข้อมูลทั้งหมด:
mysql> select * from UserInformationExpire;
ผลลัพธ์
+----+----------+-------------------------------+ | Id | UserName | UserInformationExpireDateTime | +----+----------+-------------------------------+ | 1 | Maxwell | 2019-02-09 23:56:27 | | 2 | Carol | 2018-11-21 15:45:21 | | 3 | Bob | 2019-01-22 16:30:35 | | 4 | Larry | 2017-12-25 17:20:33 | +----+----------+-------------------------------+ 4 rows in set (0.00 sec)
ไวยากรณ์สำหรับอัปเดต datetime เพิ่ม 5 วัน/ชั่วโมง/นาที/วินาที สำหรับ id = 1 (วันที่ปัจจุบันคือ 2019-02-09 จะกลายเป็น 2019-02-14):
mysql> update UserInformationExpire set UserInformationExpireDateTime = now() + interval 5 day where Id = 1; Query OK, 1 row affected (0.24 sec) Rows matched: 1 Changed: 1 Warnings: 0
ตรวจสอบข้อมูลอีกครั้งเพื่อยืนยันว่าอัปเดตเฉพาะ id 1:
mysql> select * from UserInformationExpire where Id = 1;
ผลลัพธ์
+----+----------+-------------------------------+ | Id | UserName | UserInformationExpireDateTime | +----+----------+-------------------------------+ | 1 | Maxwell | 2019-02-14 23:56:27 | +----+----------+-------------------------------+ 1 row in set (0.00 sec)