2012-10-25 176 views
16

在現有的數據庫中,我使用了年齡列(INT)。現在我需要將它設置爲dob(DATETIME)。通過phpmyadmin的MySQL默認日期時間

我嘗試通過PHPMyAdmin進行操作,將CURRENT_TIMESTAMP設置爲answer with 138 upvotes定義的默認值。然而phpMyAdmin是抱怨#1067 - invalid default value for 'dob'爲附截圖:

Error screenshot

可有人請說明爲什麼我收到的錯誤,以及如何解決這個問題?

+6

想知道出生日期可以有當前時間作爲默認值嗎? –

+0

[DATETIME Vs TIMESTAMP](http://stackoverflow.com/questions/409286/datetime-vs-timestamp) –

+0

@Mithun。只是暫時的價值。後來會隨着其他值改變。 –

回答

18

You can't set CURRENT_TIMESTAMP作爲DATETIME的默認值。

但是你可以用TIMESTAMP做到這一點。

查看區別here。從this博客

在數據類型規範的默認值子句

詞表示用於一列的默認值。有一個例外,默認值必須是常數;它不能是一個函數或表達式。

這意味着,例如,您不能將日期列的默認值設置爲NOW()或CURRENT_DATE等函數的值。

例外是,您可以指定CURRENT_TIMESTAMP作爲TIMESTAMP列的默認值。

+0

謝謝。我用null作爲臨時值。最初我試圖通過'not null'並使用當前日期作爲默認值,但似乎這是不可能的。暫時允許null,它工作。 –

0

由於默認值current_timeDATETIME類型無效,因此會出現該錯誤。這就是它說的,這就是發生了什麼。

您可以使用current_time的唯一字段是時間戳。

2

我不認爲你可以實現與MySQL日期。你必須使用時間戳或嘗試此方法..

CREATE TRIGGER table_OnInsert BEFORE INSERT ON `DB`.`table` 
FOR EACH ROW SET NEW.dateColumn = IFNULL(NEW.dateColumn, NOW()); 
0

的日期時間的最好方法是使用觸發器:

/************ ROLE ************/ 
drop table if exists `role`; 
create table `role` (
    `id_role` bigint(20) unsigned not null auto_increment, 
    `date_created` datetime, 
    `date_deleted` datetime, 
    `name` varchar(35) not null, 
    `description` text, 
    primary key (`id_role`) 
) comment=''; 

drop trigger if exists `role_date_created`; 
create trigger `role_date_created` before insert 
    on `role` 
    for each row 
    set new.`date_created` = now(); 
0

設置爲時間戳字段的類型了。

enter image description here