在 MySQL 中將日期時間插入到另一日期時間欄位中?


你可以藉助 update 命令來實現此目的。為了理解此方法,讓我們建立一個表。建立表的查詢如下 −

mysql> create table AddDateTimeWithOther
   −> (
   −> Id int,
   −> IssueDate datetime,
   −> DueDate datetime
   −> );
Query OK, 0 rows affected (0.69 sec)

使用 insert 語句在表中插入一些記錄。查詢如下 −

mysql> insert into AddDateTimeWithOther values(100,now(),date_add(now(),interval -3 year));
Query OK, 1 row affected (0.13 sec)

mysql> insert into AddDateTimeWithOther values(101,now(),date_add(now(),interval 2 year));
Query OK, 1 row affected (0.20 sec)

使用 select 語句顯示錶中的所有記錄。查詢如下 −

mysql> select *from AddDateTimeWithOther;

以下是輸出 −

+------+---------------------+---------------------+
| Id   | IssueDate           | DueDate             |
+------+---------------------+---------------------+
| 100 | 2018-12-11 17:33:28 | 2015-12-11 17:33:28  |
| 101 | 2018-12-11 17:33:37 | 2020-12-11 17:33:37  |
+------+---------------------+---------------------+
2 rows in set (0.00 sec)

現在,如果你想在 “DueDate” ‘2015-12-11 17:33:28’ 的位置設定另一個日期,那麼使用 UPDATE 命令。下面的查詢顯示了將到期日期更新為 ‘2019-12-11 17:35:03’ 的相同內容。

查詢如下 −

mysql> update AddDateTimeWithOther set DueDate = date_add(now(),interval 1 year) where Id = 100;
Query OK, 1 row affected (0.24 sec)
Rows matched: 1 Changed: 1 Warnings: 0

現在,你可以檢查資料是否已經插入。查詢如下 −

mysql> select *from AddDateTimeWithOther;

以下是顯示更新成功和已插入日期的輸出 −

+------+---------------------+---------------------+
| Id   | IssueDate           | DueDate             |
+------+---------------------+---------------------+
| 100  | 2018-12-11 17:33:28 | 2019-12-11 17:35:03 |
| 101  | 2018-12-11 17:33:37 | 2020-12-11 17:33:37 |
+------+---------------------+---------------------+
2 rows in set (0.00 sec)

更新於: 2019-07-30

414 次檢視

開啟你的 職業

完成課程,獲得認證

開始
廣告