4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MySQLでINSERT時にDATETIME型のカラムに指定した時刻のミリ秒が四捨五入される

Last updated at Posted at 2014-02-27
CREATE TABLE `datetimetest` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
);

上記のようなテーブルを用意します。datetimeは括弧なしなので秒単位です。

mysql> INSERT INTO datetimetest set time='2014-01-01 00:00:00.499';
mysql> INSERT INTO datetimetest set time='2014-01-01 00:00:00.500';
mysql> SELECT * FROM datetimetest;
+----+---------------------+
| id | time                |
+----+---------------------+
|  1 | 2014-01-01 00:00:00 |
|  2 | 2014-01-01 00:00:01 |
+----+---------------------+

こんなふうにINSERT時にミリ秒まで指定すると、ミリ秒が四捨五入されて秒が進んでしまいます。

mysql> SELECT * FROM datetimetest WHERE time<='2014-01-01 00:00:00.999';
+----+---------------------+
| id | time                |
+----+---------------------+
|  1 | 2014-01-01 00:00:00 |
+----+---------------------+
mysql> SELECT * FROM datetimetest WHERE time>='2014-01-01 00:00:00.999';
+----+---------------------+
| id | time                |
+----+---------------------+
|  2 | 2014-01-01 00:00:01 |
+----+---------------------+
mysql> SELECT * FROM datetimetest WHERE time>='2014-01-01 00:00:00.100';
+----+---------------------+
| id | time                |
+----+---------------------+
|  2 | 2014-01-01 00:00:01 |
+----+---------------------+

条件式にミリ秒を含む時刻を指定するとそれはそのまま扱われるようです。


追記:MySQL5.5では再現しないとの情報あり。MySQL5.6以降のみで発生する現象かも?

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?