MySQL儲存毫秒資料的方法_Mysql

來源:互聯網
上載者:User

有相當一部分剛接觸到 MySQL 的朋友都遇到這樣一個相同的問題,就是關於毫秒的儲存與顯示。由於MySQL資料類型中只提供了DATETIME, TIMESTAMP, TIME, DATE, YEAR這幾種時間類型,而且DATETIME 以及 TIMESTAMP 的最小單位是秒,沒有儲存毫秒層級的函數。 不過MySQL卻能識別時間中的毫秒部分。而且我們有多種方式可以獲得毫秒的部分,比如函數:microsecond 等。

我這裡舉一個簡單的例子,來儲存秒之前和之後的部分。
對於把時間欄位作為主鍵的應用,我們可以建立以下的表來作相應的轉化:

mysql> create table mysql_microsecond ( log_time_prefix timestamp not null default 0, log_time_suffix mediumint not null default 0) engine innnodb;Query OK, 0 rows affected, 2 warnings (0.00 sec)
mysql> alter table mysql_microsecond add primary key (log_time_prefix, log_time_suffix);Query OK, 0 rows affected (0.01 sec)Records: 0 Duplicates: 0 Warnings: 0
mysql> set @a = convert(concat(now(),'.222009'),datetime);Query OK, 0 rows affected (0.00 sec)
mysql> insert into mysql_microsecond select date_format(@a,'%Y-%m-%d %H-%i-%s'),date_format(@a,'%f');Query OK, 1 row affected (0.00 sec)Records: 1 Duplicates: 0 Warnings: 0
mysql> select * from mysql_microsecond;+---------------------+-----------------+| log_time_prefix   | log_time_suffix |+---------------------+-----------------+| 2009-08-11 17:47:02 |     222009 |+---------------------+-----------------+1 row in set (0.00 sec)


或者是用VARCHAR來儲存所有的時間欄位, 又或者是儲存一個HASH來保證效能!
方法很多,就看你的應用怎麼用合理了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.