由于MySQL目前字段的默認(rèn)值不支持函數(shù),所以用create_time datetime default now()的形式設(shè)置默認(rèn)值是不可能的.
代替的方案是使用TIMESTAMP類型代替DATETIME類型.
CURRENT_TIMESTAMP:當(dāng)我更新這條記錄的時(shí)候,這條記錄的這個(gè)字段不會改變.
CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP:當(dāng)我更新這條記錄的時(shí)候,這條記錄的這個(gè)字段將會改變,即時(shí)間變?yōu)榱烁聲r(shí)候的時(shí)間.
注意一個(gè)UPDATE設(shè)置一個(gè)列為它已經(jīng)有的值,這將不引起TIMESTAMP列被更新,因?yàn)槿绻阍O(shè)置一個(gè)列為它當(dāng)前的值,MySQL為了效率而忽略更改,如果有多個(gè)TIMESTAMP列,只有第一個(gè)自動(dòng)更新.
下面為您介紹MySQL設(shè)置當(dāng)前時(shí)間為默認(rèn)值的實(shí)現(xiàn)全步驟:
數(shù)據(jù)庫:test_db1
創(chuàng)建表:test_ta1
字段:
id 編號,自增 且為主鍵,createtime 創(chuàng)建日期,默認(rèn)值為當(dāng)前時(shí)間.
方法一,用alert table語句創(chuàng)建,代碼如下:
- use test_db1; create table test_ta1( id mediumint(8) unsigned not nulll auto_increment, createtime datetime, primary key (id) )engine=innodb default charset=gbk; alert table test_ta1 change createtime createtime timestamp not null default now();
方法二,直接創(chuàng)建,代碼如下:
- use test_db1; create table test_ta1( id mediumint(8) unsigned not nulll auto_increment, createtime timestamp not null default current_timestamp, primary key (id) )engine=innodb default charset=gbk;
方法三,使用可視化工具,如 mysql-front,創(chuàng)建.
右擊createtime屬性,把Type屬性值改為timestamp,default 屬性選擇<INSERT-TimeStamp>,以上就是MySQL設(shè)置當(dāng)前時(shí)間為默認(rèn)值的方法介紹.
新聞熱點(diǎn)
疑難解答
圖片精選