简体   繁体   中英

Best way to store exact duration in mysql

I use the TIME field quite frequently to store a second-accurate duration. However, how would I store something like:

4 hours, 3 minutes, 1.1828999 second

I would prefer not to store it as a float or decimal, but in a way that is clear it's a time duration. How should I do this?

Store it as a TIME(6) to get up to six digits of precision for fractional seconds. Time precision is a feature introduced in MySQL 5.6.

Storage of fractional seconds costs an extra 3 bytes per column. See https://dev.mysql.com/doc/refman/5.6/en/storage-requirements.html#data-types-storage-reqs-date-time for details.

Then you can format it as you select the value:

mysql> select current_time(6), 
 date_format(current_time(6), '%H hours, %i minutes, %s.%f seconds') as `formatted time`;
+-----------------+-----------------------------------------+
| current_time(6) | formatted time                          |
+-----------------+-----------------------------------------+
| 00:24:53.843700 | 00 hours, 24 minutes, 53.843700 seconds |
+-----------------+-----------------------------------------+

See DATE_FORMAT() for other formatting options.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM