sql mysql 日期型別及預設設定

2021-09-02 19:59:28 字數 2922 閱讀 6733

mysql 的日期型別如何設定當前時間為其預設值? 

答:請使用 timestamp 型別,且 預設值設為 now() 或 current_timestamp() 。

型別

位元組格式

用途是否支援設定系統預設值

date

3yyyy-mm-dd

日期值不支援

time

3hh:mm:ss

時間值或持續時間

不支援year

1yyyy

年份不支援

datetime

8yyyy-mm-dd hh:mm:ss

日期和時間混合值

不支援timestamp

4yyyymmdd hhmmss

混合日期和時間,可作時間戳

支援

關於 default 設定,通常情況下會使用當前時間作為預設值。 

example:

ts_time timestamp not null default now();
ts_time timestamp not null default current_timestamp();
如果建表語句中有:

ts_time1 time not null default now();

ts_time3 yearnot null default now();

ts_time2 date not null default current_timestamp();

ts_time2 datetime not null default current_timestamp();

都會報錯。所以想要設定某個日期列的預設值為當前時間,只能使用 timestamp 型別,並設定 default now() 或 default current_timestamp() 作為預設值。

date 型別預設值使用 current_date() 建立失敗

date 型別預設值使用 now() 建立失敗

date 型別預設值使用 current_timestamp() 建立失敗

datetime 型別預設值使用 current_timestamp() 建立失敗

datetime 型別預設值使用 now() 建立失敗

timestamp 型別預設值使用 now() 建立成功

mysql中有一些日期函式可供我們使用,我們可以使用 」 select 函式名() ; 」 的 sql 檢視它們的返回值。同時也可以使用 「select 自定義函式名();」,呼叫我們自己定義的函式。 

函式

描述now()

返回當前的日期和時間

curdate()

返回當前的日期

curtime()

返回當前的時間

date()

提取日期或日期/時間表示式的日期部分

extract()

返回日期/時間按的單獨部分

date_add()

給日期新增指定的時間間隔

date_sub()

從日期減去指定的時間間隔

datediff()

返回兩個日期之間的天數

date_format()

用不同的格式顯示日期/時間

原文參考:

MySQL 日期型別及預設設定

mysql 的日期型別如何設定當前時間為其預設值?答 請使用 timestamp 型別,且 預設值設為 now 或 current timestamp 型別 位元組格式 用途是否支援設定系統預設值 date 3yyyy mm dd 日期值不支援 time 3hh mm ss 時間值或持續時間 不支援...

sql mysql 日期函式 今天昨天

mysql 今天和昨天日期及格式化 今天日期 時間 select now 返回2018 04 25 17 33 21 今天日期 select curdate 返回2018 04 25 今天日期格式化 select date format curdate y m d 返回2018 04 25 昨天日期...

SQL (MySQL)基礎知識 資料型別

整型浮點型,例如double 3,2 表示最多3位,其中必須有2位小數,即最大值為9.99 浮點型,字串儲存,表單錢方面推薦使用,不會出現精度缺失問題 固定長度字串型別,最多255個字元,資料長度不足指定長度,補足到指定長度 可變長度字串型別,備忘錄推薦使用,如果值的長度大於 255,則被轉換為te...