MYSQL中TIMESTAMP類型的使用

來源:互聯網
上載者:User

MYSQL中TIMESTAMP類型的預設值
  
MYSQL中TIMESTAMP類型可以設定預設值,就像其他類型一樣。
1、自動UPDATE 和INSERT 到當前的時間:
表:
---------------------------------
Table   Create Table                                                                        
------  -------------------------------------------------------------------------------------
t1      CREATE TABLE `t1` (                                                                  
          `p_c` int(11) NOT NULL,                                                            
          `p_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP  
        ) ENGINE=InnoDB DEFAULT CHARSET=gb2312                                               
資料:
1    2007-10-08 11:53:35
2    2007-10-08 11:54:00
insert into t1(p_c) select 3;
update t1 set p_c = 2 where p_c = 5;
資料:
1    2007-10-08 11:53:35
5    2007-10-08 12:00:37
3    2007-10-08 12:00:37

2、自動INSERT 到目前時間,不過不自動UPDATE。
表:
---------------------------------
Table   Create Table                                             
------  ---------------------------------------------------------
t1      CREATE TABLE `t2` (                                      
          `p_c` int(11) NOT NULL,                                
          `p_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP  
        ) ENGINE=InnoDB DEFAULT CHARSET=gb2312                  
資料:
insert into t2(p_c) select 4;
update t2 set p_c = 3 where p_c = 5;
1    2007-10-08 11:53:35
2    2007-10-08 12:00:37
5    2007-10-08 12:00:37
4    2007-10-08 12:05:19

3、一個表中不能有兩個欄位預設值是目前時間,否則就會出錯。不過其他的可以。
表:
---------------------------------
Table   Create Table                                                   
------  ---------------------------------------------------------------
t1      CREATE TABLE `t1` (                                            
          `p_c` int(11) NOT NULL,                                      
          `p_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,      
          `p_timew2` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'  
        ) ENGINE=InnoDB DEFAULT CHARSET=gb2312                        
資料:
1    2007-10-08 11:53:35    0000-00-00 00:00:00
2    2007-10-08 12:00:37    0000-00-00 00:00:00
3    2007-10-08 12:00:37    0000-00-00 00:00:00
4    2007-10-08 12:05:19    0000-00-00 00:00:00

一般在資料庫結構設計中,用datetime替換timestamp欄位,用程式來實現時間的建立和修改,這樣可以控制的更加準確,好處是,不至於你修改該表的任何資料,此時間會隨之改變。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.