我可以为 MySQL 中的每条记录获取唯一的 TIMESTAMP [英] Can I get a unique TIMESTAMP for every record in MySQL

查看:17
本文介绍了我可以为 MySQL 中的每条记录获取唯一的 TIMESTAMP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能为 MySQL 中的每条记录获取唯一的时间戳值??..

Is there a possibility of getting a unique timestamp value for for each record in MySQL??..

我创建了一个示例表

CREATE TABLE t1 (id int primary key, name varchar(50), 
  ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP );

并运行了一些示例 INSERTIONS,似乎时间戳值重复.

and ran some sample INSERTIONS and seems to be timestamp values are duplicated.

e.g  insert into t1(id,name) values(1,"test");

推荐答案

不久的将来(5.6.4),MySQL 将提供 小数秒 在 TIMESTAMP 列中,但是,即使小数秒也不能保证是唯一的,尽管理论上,它们通常是唯一的,特别是如果您将 MySQL 限制为单个线程.

Some day soon (5.6.4), MySQL will provide fractional seconds in TIMESTAMP columns, however, even fractional seconds aren't guaranteed to be unique, though theoretically, they'd most often be unique, especially if you limited MySQL to a single thread.

您可以使用 UUID 如果您需要一个按时间排序的唯一编号.

You can use a UUID if you need a unique number that is ordered temporally.

SELECT UUID() 产生类似:

45f9b8d6-8f00-11e1-8920-842b2b55ce56

一段时间后:

004b721a-8f01-11e1-8920-842b2b55ce56

UUID 的前三个部分由时间组成,但是,它们的顺序是从最高精度到最小精度,因此您需要使用 SUBSTR() 反转前三个部分和 CONCAT() 像这样:

The first three portions of a UUID consist of the time, however, they're in order from highest precision to least, so you'd need to reverse the first three portions using SUBSTR() and CONCAT() like this:

SELECT CONCAT(SUBSTR(UUID(), 15, 4), '-', SUBSTR(UUID(), 10, 4),
  '-', SUBSTR(UUID(), 1, 8))

产量:

11e1-8f00-45f9b8d6

你显然不能使用这样的函数作为默认值,所以你必须在代码中设置它,但它是一个保证唯一的时间排序值.UUID() 在比秒(时钟周期)低得多的水平上工作,因此每次调用都保证它是唯一的,并且开销低(没有像 auto_increment 这样的锁定).

You obviously couldn't use a function like this as a default value, so you'd have to set it in code, but it's a guaranteed unique temporally ordered value. UUID() works at a much lower level than seconds (clock cycles), so it's guaranteed unique with each call and has low overhead (no locking like auto_increment).

在数据库服务器上使用 UUID() 可能优于在应用程序服务器上使用类似函数,例如 PHP 的 microtime() 函数,因为您的数据库服务器更加集中.您可能有多个应用程序(Web)服务器,这可能会产生冲突值,并且 microtime() 仍然不能保证唯一值.

Using the UUID() on the database server may be preferred to using a similar function, such as PHP's microtime() function on the application server because your database server is more centralized. You may have more than one application (web) server, which may generate colliding values, and microtime() still doesn't guarantee unique values.

这篇关于我可以为 MySQL 中的每条记录获取唯一的 TIMESTAMP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆