MySQL數據庫TIMESTAMP設置默認值是本文我們主要要介紹的內容,我們知道,CURRENT_TIMESTAMP :當我更新這條記錄的時候,這條記錄的這個字段不會改變。
CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP :當我更新這條記錄的時候,這條記錄的這個字段將會改變。即時間變為了更新時候的時間。注意一個UPDATE設置一個列為它已經有的值,這將不引起TIMESTAMP列被更新,因為如果你設置一個列為它當前的值,MySQL為了效率而忽略更改。)
如果有多個TIMESTAMP列,只有第一個自動更新。
接下來我們看幾個實際的例子:
#1創建一個有兩個timestamp字段的表dj1。
- root@localhost:test >create table dj1 (a char(1), b timestamp ,c timestamp);
- Query OK, 0 rows affected (0.01 sec)
#2插入兩行數據,僅賦值於列A
- root@localhost:test >insert into dj1 values (1,null,null);
- Query OK, 1 row affected (0.00 sec)
- root@localhost:test >insert into dj1 values (2,null,null);
- Query OK, 1 row affected (0.00 sec)
#3查詢插入數據,b,c兩列都使用current timestamp作為默認值。
- root@localhost:test >select * from dj1;
- +------+---------------------+---------------------+
- | a | b | c |
- +------+---------------------+---------------------+
- | 1 | 2009-09-09 13:48:40 | 2009-09-09 13:48:40 |
- | 2 | 2009-09-09 13:48:44 | 2009-09-09 13:48:44 |
- +------+---------------------+---------------------+
- 2 rows in set (0.00 sec)
#4更新一行數據,發現b列timestamp被自動更新,而c列保持不變。
- root@localhost:test >update dj1 set a=9 where a=1;
- Query OK, 1 row affected (0.00 sec)
- Rows matched: 1 Changed: 1 Warnings: 0
- root@localhost:test >select * from dj1;
- +------+---------------------+---------------------+
- | a | b | c |
- +------+---------------------+---------------------+
- | 9 | 2009-09-09 13:49:08 | 2009-09-09 13:48:40 |
- | 2 | 2009-09-09 13:48:44 | 2009-09-09 13:48:44 |
- +------+---------------------+---------------------+
- 2 rows in set (0.00 sec)
#5再更新一列,仍然如#4
- root@localhost:test >update dj1 set a=8 where a=2;
- Query OK, 1 row affected (0.00 sec)
- Rows matched: 1 Changed: 1 Warnings: 0
- root@localhost:test >select * from dj1;
- +------+---------------------+---------------------+
- | a | b | c |
- +------+---------------------+---------------------+
- | 9 | 2009-09-09 13:49:08 | 2009-09-09 13:48:40 |
- | 8 | 2009-09-09 13:49:36 | 2009-09-09 13:48:44 |
- +------+---------------------+---------------------+
- 2 rows in set (0.00 sec)
#6在b列上創建唯一索引
- root@localhost:test >create unique index dj1_idx_u1 on dj1(b);
- Query OK, 2 rows affected (0.01 sec)
- Records: 2 Duplicates: 0 Warnings: 0
#7更新所有行a列,報唯一性沖突。
- root@localhost:test >update dj1 set a=1;
- ERROR 1062 (23000): Duplicate entry '2009-09-09 13:54:45' for key 'dj1_idx_u1'
結論:
1.MySQL默認表的第一個timestamp字段為NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP屬性,必須顯式定義改變這種行為。
2.MySQL只允許一個timestamp字段擁有[DEFAULT CURRENT_TIMESTAMP |ON UPDATE CURRENT_TIMESTAMP]屬性。 我的理解為要麼都是DEFAULT CURRENT_TIMESTAMP 要麼都是DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
3.修改字段屬性值
- show create table tbl_ledgerrecord;
- alter table tbl_ledgerrecord change intoStorageDate intoStorageDate timestamp DEFAULT CURRENT_TIMESTAMP;
關於MySQL數據庫TIMESTAMP設置默認值的靈活運用的知識就介紹到這裡了,希望本次的介紹能夠對您有所收獲!