MySQL method of storing millisecond data

  • 2020-06-15 10:24:33
  • OfStack

Quite a few people who are new to MySQL have the same problem with millisecond storage and display. Since only DATETIME, TIMESTAMP, TIME, DATE, YEAR are provided in MySQL data types, and the minimum unit of DATETIME and TIMESTAMP is seconds, there is no function that stores the millisecond level. MySQL, however, recognizes milliseconds of time. And there are several ways to get the milliseconds, such as the function microsecond.

I'll take a simple example here to store the parts before and after seconds.
For applications where the time field is used as the primary key, we can create the following table to translate accordingly:


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)


Either store all the time fields with VARCHAR, or store 1 HASH for performance!
There are a lot of ways, depending on how you use your application.


Related articles: