简体   繁体   English

在MySQL数据库中存储时间跨度的最佳方法?

[英]Best way to store span on time in a MySQL database?

I'd like to store an amount of time for something in a mysql database,for the length of time something took, such as 2 hours, 5 minutes, 10 seconds. 我想将某物的时间存储在mysql数据库中,以花费某物的时间长度,例如2小时5分10秒。 accuracy down to the second is preferred, but not required. 精度低至秒是首选,但不是必需的。 What's the best way to go about doing this? 这样做的最佳方法是什么?

A MySQL TIME type can store time spans from '-838:59:59' to '838:59:59' - if that's within your required range, and it would be useful to have MySQL natively present these spans in HH:MM:SS form, then use that. MySQL TIME类型可以存储从'-838:59:59'到'838:59:59'的时间范围-如果在您要求的范围之内,那么让MySQL在HH:MM中本地显示这些时间范围将很有用: SS表格,然后使用该表格。

Otherwise, I'd just go with an integer type to represent the number of seconds. 否则,我将使用整数类型来表示秒数。

I like storing things in the database as base units. 我喜欢将事物作为基本单位存储在数据库中。 That way I can reliably and accurately convert to anything else I want later on. 这样,以后我就可以可靠,准确地转换为其他任何想要的东西。

The only thing you have to worry about with this method is getting your precision down. 使用此方法唯一需要担心的是降低精度。 If you are storing distance traveled for cross country trips, inches or centimeters might not be what you are looking for. 如果您要存储越野旅行的旅行距离,英寸或厘米可能不是您想要的。

In your case, I'd store the span as seconds or milliseconds and go from there. 在您的情况下,我将跨度存储为秒或毫秒,然后从那里开始。

As Andrew says, an integer field with seconds might do already. 正如安德鲁所说,一个带有秒的整数字段可能已经做过。

If the data is available, and it makes sense to store it, I would save the data in two mySQL timestamps with the start and end times (also possibly great for auditing later), and use DATE_DIFF() to fetch the actual duration. 如果数据可用,并且有存储的意义,那么我会将数据保存在带有开始和结束时间的两个mySQL时间戳中(也可能对以后的审核很有用),并使用DATE_DIFF()获取实际持续时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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