m_shige1979のときどきITブログ

プログラムの勉強をしながら学習したことや経験したことをぼそぼそと書いていきます

Github(変なおっさんの顔でるので気をつけてね)

https://github.com/mshige1979

MySQLのDATETIMEやTIMESTAMPでミリ秒などを設定したい

環境

MySQL5.7での確認

こんな感じの定義の場合

drop table if exists sample1;
create table if not exists sample1(
    id bigint       not null auto_increment,
    date1 datetime  not null,
    date2 timestame not null,
    primary key(id)
);

insert into sample1(date1, date2) values(current_timestamp, current_timestamp);

+----+---------------------+---------------------+
| id | date1               | date2               |
+----+---------------------+---------------------+
|  1 | 2016-12-30 11:04:16 | 2016-12-30 11:04:16 |
+----+---------------------+---------------------+

※秒までしか設定されていない感じ

内部的に値が設定されていたとしても取得した際の値が秒までの場合はミリ秒まで取得したくても対応できない

ミリ秒を設定したデータをinsertしてみる

insert into sample1(date1, date2) values('2016-12-30 11:04:16.123', '2016-12-30 11:04:16.123');

+----+---------------------+---------------------+
| id | date1               | date2               |
+----+---------------------+---------------------+
|  1 | 2016-12-30 11:04:16 | 2016-12-30 11:04:16 |
+----+---------------------+---------------------+

だめです(´・ω・`)

TIMESTAMPやDATETIMEに小数桁数を指定

drop table if exists sample1;
create table if not exists sample1(
    id bigint       not null auto_increment,
    date1 datetime(3)  not null,
    date2 timestamp(3) not null,
    primary key(id)
);

insert into sample1(date1, date2) values(current_timestamp, current_timestamp);

+----+-------------------------+-------------------------+
| id | date1                   | date2                   |
+----+-------------------------+-------------------------+
|  1 | 2016-12-30 11:14:03.000 | 2016-12-30 11:14:03.000 |
+----+-------------------------+-------------------------+

※小数桁を表現するようになった

小数桁のデータでinsert

insert into sample1(date1, date2) values('2016-12-30 11:04:16.123', '2016-12-30 11:04:16.123');

+----+-------------------------+-------------------------+
| id | date1                   | date2                   |
+----+-------------------------+-------------------------+
|  1 | 2016-12-30 11:04:16.123 | 2016-12-30 11:04:16.123 |
+----+-------------------------+-------------------------+

※設定できた(^^)

nowやcurrent_timestampでミリ秒を設定する

select now(3), current_timestamp(3), current_time(3);

+-------------------------+-------------------------+-----------------+
| now(3)                  | current_timestamp(3)    | current_time(3) |
+-------------------------+-------------------------+-----------------+
| 2016-12-30 11:18:43.408 | 2016-12-30 11:18:43.408 | 11:18:43.408    |
+-------------------------+-------------------------+-----------------+

※括弧内に桁数を指定すればミリ秒などを表示してくれる(^^)

わかったこと

  • DATETIMEやTIMESTAMPはミリ秒は定義時などで指定しないと値を設定しても正しく設定してくれない恐れがある
  • 最大6桁の小数桁を格納できる

期待

うーん、なんか設定ファイルでこの辺簡単に対応したいな〜
まあ使用する言語でどこまで保証するとかあるから難しいかも